How to override Magento model classes?

本文介绍如何在不修改Magento核心文件的情况下扩展或覆盖模型类的方法。通过创建新的模块并重写特定的模型类来实现功能增强。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://inchoo.net/magento/how_to_override_magento_model_classes/

How to override Magento model classes?

Featured Image

Many times we need to implement new functionality of existing Magento core classes, but we don’t want to modify core classes.
For controllers, that’s quite easy. Usually we can copy controller from core and put it in the same place in local directory, modify class and that’s it.

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
there.

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"?>  
<config>  
    <modules>  
        <inchoo_wishlist>  
            <active>true</active>  
            <codepool>local</codepool>  
        </inchoo_wishlist>  
    </modules>  
</config> 

Now, make app/code/local/Inchoo/Wishlist/etc/Config.xml file and put this code there:

< ?xml version="1.0"?>
<config>
    <modules>
        <inchoo_wishlist>
            <version>0.1</version>
        </inchoo_wishlist>
    </modules>
    <global>
       <models>
          <wishlist>
              <rewrite>
                  <item>Inchoo_Wishlist_Model_Item</item>
              </rewrite>
          </wishlist>
       </models>
    </global>
</config>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值