Magento – Extending Mage_Core_Model_Resource_Setup in Installer Scripts

install-scriptsetup-scriptupgrade-script

Lot of time, I heard that installer script, upgrade script, and data script files are extending Mage_Core_Model_Resource_Setup (default case). When we make a look on any of these file, there is no hint for this. For example, an installer script somewhat look like this.

#FILE : app/code/<any_code_pool>/<AnyNameSpace>/<AnyModuleName>/sql/<any_script_setup>/install-x.x.x.php
$installer =  $this;
$installer->startSetup();

//some stuffs here

$installer->endSetup();

As you can see, the file does not specify any class or not extending any class explicitly. And then also several tutorial says that $this is an instance of resource setup class. How it is possible?

Can you guys give some hints about this ?

Best Answer

It all starts in Mage_Core_Model_App::_initModules. Actually it starts higher in the stack but you are interested on this.
In this method there is this line:

Mage_Core_Model_Resource_Setup::applyAllUpdates();

And the method applyAllUpdates looks like this:

static public function applyAllUpdates()
{
    Mage::app()->setUpdateMode(true);
    self::$_hadUpdates = false;

    $resources = Mage::getConfig()->getNode('global/resources')->children();
    $afterApplyUpdates = array();
    foreach ($resources as $resName => $resource) {
        if (!$resource->setup) {
            continue;
        }
        $className = __CLASS__;
        if (isset($resource->setup->class)) {
            $className = $resource->setup->getClassName();
        }
        $setupClass = new $className($resName);
        $setupClass->applyUpdates();
        if ($setupClass->getCallAfterApplyAllUpdates()) {
            $afterApplyUpdates[] = $setupClass;
        }
    }

    foreach ($afterApplyUpdates as $setupClass) {
        $setupClass->afterApplyAllUpdates();
    }

    Mage::app()->setUpdateMode(false);
    self::$_schemaUpdatesChecked = true;
    return true;
}

The interesting part is this:

        $className = __CLASS__;
        if (isset($resource->setup->class)) {
            $className = $resource->setup->getClassName();
        }
        $setupClass = new $className($resName);
        $setupClass->applyUpdates();

So if you specify a specific class for the upgrade scripts that will be instantiated, otherwise __CLASS__ (which is Mage_Core_Model_Resource_Setup) will be used.

And if you look for the method applyUpdates that is called in the code above you will end up after digging in _modifyResourceDb method in the same class where this code is what you are looking for

case 'php':
    $conn   = $this->getConnection();
    $result = include $fileName;

This means that the upgrade script is included in class you are using, hence you can access $this.

Side note: In a similar way you can access $this in template files. They are included in rendering method for blocks.