Categories
Magento

Using Magento local.xml to Override a Model/Helper/Block

Today I was modifying and debugging a Magento module and I found myself in the need to override a class of that module to make it to write to file instead of trying to send processed data to an external service (so it would have been easier to debug).

Instead to change the original class (and the restore it once done or make it configurable) I created a new class extending the original one and I overrode the single method which was used to connect externally. Of course I changed this method to write to file.

It was an helper and all the module code was (correctly) getting the helper instance via Mage::getHelper(“helper/name”).

To activate my version I should have changed the config.xml of the module but that leads to the same old problem: once ended I should have restored the original configuration.

But every configuration can be locally changed by the local.xml file. So I added to my local.xml configuration this snippet:

<helpers>
<moduletag>
<rewrite>
<helpername>My_Helper_Class_Name</helpername>
</rewrite>
</moduletag>
</helpers>

So, when the helper is requested with Mage::getHelper(‘moduletag/helpername’) my version is returned… and this is just a configuration! My class can now be part of the module and used for debugging purposes, just activating it with a local configuration while, even if present on the production environment, it does nothing.

This approach can be used by modules which have different implementations of models or helpers or blocks from which is required to choose from. It’s like a configuration but the module does not need to deal with configuration XML path and fill the code with if and switch to use the right implementation or activate the right code.

The local.xml is not used as it should to contain those configuration (even for modules) which need to be different on different servers. It would be of great help specially when the database must be periodically transferred from production to staging and the core_config_data table adjusted!

Note 1: when Magento loads the configuration, it loads ALL the .xml file found in app/etc so pay attention when you put there different copies of configuration files. Not that Magento provide some samples but they have not an .xml extension.

The loader can be found app/code/core/Mage/Core/Model/Config.php::loadBase().

Note 2: the local.xml file is loaded before the modules’ config.xml file, but at the end is re-merged to avoid modules to override the local.xml settings. So the local.xml (and the config.xml) has priority over the module configurations.

Leave a Reply