Question

Can we call model methods in Magento setup scripts? I tried this, setup script is executed (new entry appears in the database table core_resource) but model methods are not executed (I added Mage:log('test'); inside methods to check if they were fired):

$installer = $this;
$installer->startSetup();

Mage::getModel('myextension/mymodel1')->doSomething();
Mage::getSingleton('myextension/mymodel2')->doSomethingElse();

$installer->endSetup();
Was it helpful?

Solution

You can do that but it won't work in all the cases.
For this kind of problems Magento has the data folder.
For example if you create and extension and you have this install script sql/module_setup/install-0.0.1.php. Keep in this file just the table related scripts.
For data manipulation create this file data/module_setup/install-0.0.1.php. Both of them will be exectuted when installing the extension.
It works the same for upgrade scripts. Just keep in mind to have the same version in the file names from the sql and data folders.

OTHER TIPS

"No log entry" != "model methods were not called"

Setup scripts are executed very early in application initialization; in fact, they are run before the user config settings (including everything under dev) are merged into the configuration DOM. A look at the Mage::log() method (link) shows why this is an issue when there is a desire to write log entries in setup scripts:

public static function log($message, $level = null, $file = '', $forceLog = false)
{
    if (!self::getConfig()) {
        return;
    }

    try {
        $logActive = self::getStoreConfig('dev/log/active'); //this is the kicker
        if (empty($file)) {
            $file = self::getStoreConfig('dev/log/file');
        }
    }
    catch (Exception $e) {
        $logActive = true;
    }
                                    // v-- always false in setup scripts
    if (!self::$_isDeveloperMode && !$logActive && !$forceLog) {
        return;
    }
    //...
}

In data setup scripts, the store config has been merged, and you could allow the configured behavior to work. Regardless of the user configuration, the following are a couple of options:

1. Enable developer mode in your setup script:

<?php
$isDevMode = Mage::getIsDeveloperMode();
Mage::setIsDeveloperMode(true);
/*
    ...your setup script logic...
*/
//note that this global flag may have effects outside your script 
Mage::setIsDeveloperMode($isDevMode); //preserves original setting for the
                                      //remainder of the execution scope

2. Explicitly force logging in your script:

<?php
Mage::log('foo',Zend_Log::INFO,'custom.log',true); //the last param forces logging
//And, since you are enumerating the params, why not write to a custom log?
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top