Magento modules post deployment uninstall & downgrading

An interesting question on StackOverflow about Magento modules and the un-installation or downgrade of code…

[box]Automated instant rollback is an important feature of enterprise-grade deployment mechanisms. Currently, it’s not possible to achieve this using Magento’s built-in installation tools. Given that Magento’s core_resource mechanism allows for the sequential execution of setup scripts for installation or upgrade of modules (via execution of SQL and also PHP), it seems logical that it should support the same process in reverse.[/box]

I have seen some postings in regards to such and have investigated the same scenarios for SQL deployment myself. I would have to agree that being Enterprise grade Magento should have this type of functionality built-in. The good news it IS, at least in SOME form or fashion, how complete it is I’m not really sure. Here’s a sample of a rollback upon exception:

    try {
        $write = Mage::getSingleton('core/resource')->getConnection('core_write');
        $write->beginTransaction();
    // do stuff here
        $write->commit();
    } catch (Exception $e) {
        mage::log(__METHOD__ . ':' . __LINE__ . ': Rollback happened.');
        $write->rollback();
    }

Now if you take a look at app/code/core/Mage/Core/Model/Resource/Setup.php you’ll find quite a bit of interesting methods. In particular: _getModifySqlFiles, _rollbackResourceDb and _modifyResourceDb.

_modifyResourceDb is the most interesting to me, since the $actionType here can be rollback and uninstall as well – also note you can use PHP files for your setup files as well.

    // Read resource files
    $arrAvailableFiles = array();
    $sqlDir = dir($sqlFilesDir);
    while (false !== ($sqlFile = $sqlDir->read())) {
        $matches = array();
        if (preg_match('#^'.$resModel.'-'.$actionType.'-(.*)\.(sql|php)$#i', $sqlFile, $matches)) {
            $arrAvailableFiles[$matches[1]] = $sqlFile;
        }
    }

After this code executes:

    $arrModifyFiles = $this->_getModifySqlFiles($actionType, $fromVersion, $toVersion, $arrAvailableFiles);

But heres where I’m assuming core Magento devs got lost in the bowels of the EAV resource model and just left it partially complete.

    protected function _getModifySqlFiles($actionType, $fromVersion, $toVersion, $arrFiles)
    {
        $arrRes = array();
        switch ($actionType) {
            case 'install':
            case 'data-install':
    ...
            case 'rollback':
                break;
            case 'uninstall':
                break;
        }
        return $arrRes;
    }

I’ve not had a chance to really test out the above, but from just my initial investigations of the ORM that is magento and the Autoloading as well as another developer’s input on his findings as well.

Ultimately it would be ideal if we can keep all of our changes at least module wise within a version controlled system. Obviously huge data sets that need to be imported shouldn’t be managed this way but for these small incremental changes I want to push to staging, production test and if it fails pull it back one version and everything is back to normal.

Obviously theres no one ideal solution for deployment with so many clients having different requirements and needs but a general way of doing this would help with code/SQL deployment. It’s kind of ironic that Enterprise has CMS staging, and the ability for modular development of code, but the DB has not gotten as much love.

There is a related question that is noting how currently we are doing it with some specialized scripts “home-brewed” that essentially do:

Doing a MySQLDump or backup, then doing a replace on the BASE_URLs in the SQL file.

Another tool to look at would be arrow Phing.

[tip]If anyone has time to investigate the “rollback” and “uninstall” processes that seem to be implemented and report their findings would be helpful to me as well.[/tip]

More reading:
arrow Best Practicies for Magento deployment.
arrow My original SO Response.

Debugging tips & tricks with Magento Commerce

If you are new to Magento then the vast amount of code to digest can be quite overwhelming. cold_sweat However, here are some tips I’ve learned about over the past on some means to tear down Magento and figure out what’s making it work.

Zend_Debug::dump

Use Zend_Debug::dump($foo); instead of using var_dump($foo); or print_r($foo); it is essentially the same, just a wrapper with pre HTML tag for formatting and escaping of special characters.

idea More details about arrow Zend Frameworks dump method.

However there will be times that simply dumping objects to the screen can be too much and cause browser hangups or even crashes. The best practice I’ve learned is to always use the getData() method that Magento has built-in to the Varien Object, this way your not getting redundant amounts of data dumped to the screen but only the bits you really care about.


Varien Object getData, debug

Magento also has a built-in debug() method in the Varien Object as well that you can use to display data in a string representation of itself.

exclamation Keep in mind debug does NOT always get attached to every object.

idea More details about the arrow Varien Object debug method, arrow Varien Object getData method


Log files

What if your having difficulty displaying things to screen or don’t want any users to see debug output. With this in mind you can also use a built in logging function, similar to arrow Zend_Log and is essentially a wrapper as well. You can find it defined in app/Mage.php.

    /**
     * log facility (??)
     *
     * @param string $message
     * @param integer $level
     * @param string $file
     * @param bool $forceLog
     */
    public static function log($message, $level = null, $file = '', $forceLog = false)
...

And here is an example:

Mage::Log($foo);

Which will log the output the contents of $foo to /var/log/system.log by default.

You can also specify your own log file with an extra argument, your custom log file will appear in /var/log/mylogfile.log

Mage::log($foo, null, 'mylogfile.log');

You can also use combinations of functions/methods to output the contents of an array for instance:

Mage::log(var_dump($fooArray), null, 'mylogfile.log');

exclamation Logging MUST be enabled within the admin: Configuration -> Developer -> Log Settings -> Enabled = Yes


XML Configuration

Most of the time, I have have issues with my XML configurations. Since Magento is very configuration based driven, one improper case or underscore can render things useless. Magento doesn’t validate the XML or throw any errors when such are encountered but rather ignored. The best means I’ve found to figure out whats going on is to display the entire XML built from all XML configurations files with.

header("Content-Type: text/xml");
die(Mage::app()->getConfig()->getNode()->asXML());

xDebug

xDebug is probably one of the more well known and most used debugging tools available. If your IDE does support it, I would highly suggest taking the time to get your environments setup so that you can connect and use it. I’m not going to cover the general use and configuration of it, however Classy Llama has a nifty post that helps keep Magento from letting xDebug take over error handling.

arrow Classy Llama’s Enable xDebugs Error Handler

exclamation It requires modification to the Core files and cannot be extended since the class is final. Make note of your change when doing this, or merely use it on a per need basis and removing it after your done with it. You can also setup your version control to ignore any changes with it.


Built-in PHP functions

If you’re using a bare bones editor without any type of auto complete looking up available class methods can be a pain digging through Magento’s numerous files and folders. To get all available methods from any class you can use var_export, get_class_methods and get_class in combination.

print "<pre>"; var_export(get_class_methods(get_class($this)));

idea More details on: var_export(), get_class(), get_class_methods()

You can also use it in combination with Magento’s getData() to display data with key values intact.

print "<pre>"; var_export(array_keys($this->getData()));

Developer Mode

One last tip I’ve been doing lately is modifying index.php and adding ini_set('display_errors', 1); to the condition checking for the developer mode flag: MAGE_IS_DEVELOPER_MODE. By default the display_errors ini_set is commented out. Here is what my change looks like:

if (isset($_SERVER['MAGE_IS_DEVELOPER_MODE'])) {
  Mage::setIsDeveloperMode(true);
  ini_set('display_errors', 1);
}

Then use .htaccess SetEnv to enable and disable developer mode per environment:

SetEnv MAGE_IS_DEVELOPER_MODE "true"

If you have any tips or if I missed something please feel free to comment and I’ll add it to the article.

NY Luxury Taxes with discounts and Magento

The Problem: If a coupon is given that decreases a products total from being greater than $110, to less than $110 a new Tax rate / class has to be applied.

arrow http://www.nystax.gov/pdf/notices/n09_12.pdf

I eventually solved it by with making a copy of /app/code/core/Mage/Subtotal.php to /app/code/community/Mage/Subtotal.php and modifying _unitBaseCalculation(), you’ll need to make sure your Tax Class ID’s are setup the same as whats in the code, as well as using Tax Calculation Method Based On “Unit Price” for the code to execute properly, its not pretty but does the job, ultimately would be best to get the tax class ID’s some other way and use return parent::_unitBaseCalculation() towards the end to incorporate the previous magento methods but this should do the trick for now. The attribute “package_id” is an additional product attribute to determine if the product is a shoe or not. region_id 43 is NY.
Continue reading NY Luxury Taxes with discounts and Magento

Extend Magento Product Attributes API

Add the ability to create, delete and add product options to your catalog via Magento’s API. Why this type of functionality is not built-in to the existing Magento API is beyond me.  However it seems Panticz.de has put together something for us who would like to have said functionality in the API:

arrow Extend Magento Product Attribute Api | panticz.de.

:!: I have not used this myself, but while in effort to find some ability to easily create options on the fly, I happened to stumble upon this as it was pretty buried in Google results. The posting looks to be almost a year old, so I’m not confident it can offer much help with current version of Magento. If anyone takes a stab at using it let me know if it works for ya or not.