How to override Magento model classes

By April 9, 2012 No Comments

Of course, there are better ways to do that (make module), but I’m not going to write about that right now since it is not subject of this post.

I only mentioned that because we can’t do same thing for models even if we want to, so how to override Magento models without modifying core files?

Fortunately, that’s very easy =)
Let’s make one extension of that kind!

Extension we are going to  make will be useless, only difference between this extension and original class will be  class name var_dump =)

What we are  going to do now is to take a random model class from Magento core.
Let it be Mage_Wishlist_Model_Item located in app/code/core/Mage/Wishlist/Model/Item.php

What we want to do is to add new functionality to that class, so let’s make new module.

Call it Inchoo_Wishlist.

Create app/code/local/Inchoo/Wishlist/model/ directory and copy app/code/core/Mage/Wishlist/Model/Item.php

Now,  rename class Mage_Wishlist_Model_Item to Inchoo_Wishlist_Model_Item.

Add this line:

var_dump(get_class($this)); exit();

in loadByProductWishlist method

Now, let’s create Inchoo_Wishlist.xml in app/etc/modules/
Put this code there:

< ?xml version="1.0"?>

Now, make app/code/local/Inchoo/Wishlist/etc/Config.xml file and put this code there:
< ?xml version="1.0"?>

You are done! Try to add something to wishlist! =)
Play with other models as well!