My tutorial today will provide you with further knowledge of the install/upgrade workflow of Magento module and also guide you how to write install and upgrade scripts using set-up resources. Keep reading because it will be very useful for you when working with database in Magento.

The install/upgrade workflow of Magento module

When having a request, the system will check your module’s version in the file: /app/code/local/Magestore/Mymodule/etc/config.xml

…
    <modules>
        <Magestore_Mymodule>
            <version>0.1.3</version>
        </Magestore_ Mymodule>
    </modules>

Magento will continue checking in the core_resource table. The current version is on the mymodule_setup line of the database.
The folder: /app/code/local/Magestore/Mymodule/sql/mymodule_setup includes script files creating database for the module:

     mysql4-install-0.1.0.php
     mysql4-install-0.1.1.php
     mysql4-install-0.1.2.php
     mysql4-install-0.1.3.php
     mysql4-upgrade-0.1.0-0.1.1.php
     mysql4-upgrade-0.1.1-0.1.2.php
     mysql4-upgrade-0.1.2-0.1.3.php
     …

If mymodule_setup doesn’t exist in the core_resource table, Magento will run the installation script file which is compatible with the current version of the module. (In this case, it’s mysql4-install-0.1.3.php).
What happens if the lower version of the module was installed? The answer is that Magento will run the upgrade script files in turn from the current version (in core_resource table) to the version which has been set up.

Guide to write install and upgrade scripts using set-up resources
The Script to install and upgrade the workflow using sql is as below:

<?php
$installer = $this;
$installer->startSetup();
$installer->run("

DROP TABLE IF EXISTS {$this->getTable(mymodule)};
CREATE TABLE {$this->getTable(mymodule)} (
  `mymodule_id` int(11) unsigned NOT NULL auto_increment,
  `title` varchar(255) NOT NULL default '',
  `description` text NOT NULL default '',
  `status` smallint(6) NOT NULL default '0',
  `created_time` datetime NULL,
  `update_time` datetime NULL,
  PRIMARY KEY (`mymodule_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
");
$installer->endSetup();

Basically, it has 3 main parts:

  • Declaring the $install variable
$installer = $this;
$installer->startSetup();
  • Writing the sql code to create the database
$installer->run("
 	//sql code here
");
  • Ending
$installer->endSetup();

Nice code! 😉

Author

Why Magestore? We believe in building a meaningful & long-term relationship with you.

Write A Comment