Magento for Developers: Class Overrides

Magento has a pretty neat system that allows developers to easily override a core class by defining a rewrite in a modules’s config.xml file. This works thanks to Magento factory names, instead of doing the traditional class instantiation, like:

$category = new Mage_Catalog_Model_Category();

we can just call Mage::getModel($key), like:

$category = Mage::getModel(‘catalog/category’);

By rewriting a factory name we can easily tell Magento to use our new class instead of the core one.

To properly override a Core class we need to define it to extend our original class, that way we can keep all the original class functionality and just override or add the functions that we actually need to change, this allows for overrides to be easier to upgrade and maintain.

However, there is another catch. Our new methods could easily leave out functionality from the original one or change the return type of the actual method. Thankfully, there is an easy way to avoid this, since we are extending the original class, we can call the original method using PHP’s parent:: construct.

PHP’s parent:: construct allows us to call the original method from the class that is being extended, ensuring that any return values or important code in the parent class is run. This will reduce the changes of breaking the system by missing an important part of code or returning the wrong value type.

Note: The risk is reduced, however, you as the developer still have the responsibility of making sure that the custom code you are returning, returns and uses the same variables and objects as the original method.

Also – on a side note, while there is a possibility to override a class by directly placing a copy on the corresponding local code pool, I wouldn’t recommend it since is harder to maintain, debug and doesn’t give us the finer control that we get from proper overrides.

Magento upgradability has always been a little bumpy, so as Magento developers, it is our responsibility to make sure changes to the core are done to a minimum, and that those changes are done in a clean and maintainable way.