Install and upgrade custom module in Magento

Magento automatically installs or upgrades any module that it encounters during runtime. The installation files are located under YourModule/sql/yourmodule_setup/mysql4-install-X.Y.Z.php. The trigger for running this file is that your module’s version number is not present in the DB table `core_resource` and that you have defined a version number in your module’s etc/config.xml file. You will also need to define a global resource for your module’s setup, use a tag name of <yourmodule_setup>. Without the resource definition that includes both setup module and a connection, the installation or upgrade will not perform, even if you increase the version number.

etc/config.xml

?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0"?>
<config>
      <modules>
            <Company_YourModule>
                  <version>1.1.0</version>
            </Company_YourModule>
      </modules>
      <global>
            <resources>
                  <yourmodule_setup>
                        <setup>
                              <module>Company_YourModule</module>
                        </setup>
                        <connection>
                              <use>core_setup</use>
                        </connection>
                  </yourmodule_setup>
            </resources>
      </global>
</config>

Given that XML file, and an absence of any record containing company_yourmodule in table `core_resource`, your module’s install file will be run the next time that module is executed. Once installed, upgrades can be triggered when you change the version number in the XML configuration file to be greater than the value in table `core_resource`. This will trigger a succession of any YourModule/sql/yourmodule_setup/mysql4-upgrade-X.Y.Z.php file that has a version number greater than the number found in the `core_resource` table.

Install module file sample: mysql4-install-1.0.0.php

?
01
02
03
04
05
06
07
08
09
10
11
<?php
 
$installer = $this;
 
$installer->startSetup();
 
$installer->run("INSERT INTO {$this->getTable('core_config_data')} (`path`, `value`) VALUES ('onestepcheckout/general/geoip_database', 'GeoIp/GeoLiteCity.dat')");
 
$installer->endSetup();
 
?>

Upgrade module file sample: mysql4-upgrade-1.0.0-1.1.0.php

?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
<?php
 
$installer = $this;
$installer->startSetup();
 
$resource = Mage::getResourceModel('sales/order_collection');
if(!method_exists($resource, 'getEntity')){
 
    $table = $this->getTable('sales_flat_order');
    $query = 'ALTER TABLE `' . $table . '` ADD COLUMN `onestepcheckout_customercomment` TEXT CHARACTER SET utf8 DEFAULT NULL';
    $connection = Mage::getSingleton('core/resource')->getConnection('core_write');
    try {
        $connection->query($query);
    } catch (Exception $e) {
 
    }
}
 
$installer->endSetup();
?>

Revisions

No comments yet.

Leave a Reply