How to Override/Rewrite Magento core blocks, models, helpers and controllers

In this Magento module tutorial, we will learn about overriding/rewriting Magento Core blocks, models, helpers and Controllers. This will force Magento to use our magento module’s class instead of using its core classes
Why this is important for every Magento developer?
  • Everytime magento release a new version, all core classes are replaced with completely new ones and so, custom code in core classes will be overriden
  • Custom code is put inside our module files so it’s very helpful in sell module on Magento Connect

Now, lets get started

Magento Blocks

Assuming that we have to change or add a function in Mage_Catalog_Block_Product class, now we will override this class so that we don’t need to change the core file (core files should not be changed in any situation).

To override this class, open config.xml and put the following code inside the tags

Next, we define a new class in the block folder of our custom module Mgtexplorer/new/Block/Catalog/Product.php

From now, whenever a catalog or product block’s object is created, Magento will make the object of our class, not the core class. Now we can make any changes here, for example: add new functions, change existing functions

Magento Models

We can also override models. For example, we’re going to override Mage_Catalog_Model_Product class, open config.xml and insert the following code:

and our extended class would be

Magento Helpers

We can also override Helpers, in this tutorial we will override Mgtexplorer_Test_Helper_Data class, put the following code to config.xml file

Similarly, define the custom Helper class in our custom module file.

Note: we can only override classes which Magento creates objects for, there are many classes that cannot be overridden like abstract class Mage_Catalog_Block_Product_Abstract… In short, if a class is just extended but Magento doesn’t create objects for it => Overriding will not work.

Magento Controllers

Overriding a core controller is a little bit different:

  • Overriding controller  is based on URL, not path of class
  • The controller file which you extend needs to be required

Next, make a custom controller at Mgtexplorer/Test/controllers/Checkout/CartController.php

My last words

Although these are very basic examples, they show you the basis of overriding the core blocks, models, helpers and controllers and you can base on my tutorial to make things more useful.

Feels free to drop comment/feedbacks, good luck with coding!

How to Override/Rewrite Magento core blocks, models, helpers and controllers
5 (100%) 1 vote


About Author

Daniel is a Magento developer with 5 years of experience with customizing Magento extensions, Magento templates. He's main author at Magento explorer

Leave A Reply