Magento 具有更改或添加类功能的工具,称为类覆盖或类重写。以下示例假定命名空间为“Custom”,模块名称为“Nav”。
首先,注册一个模块:
<?xml version="1.0" encoding="UTF-8"?>
<!-- app/etc/modules/whatever.xml -->
<config>
<modules>
<Custom_Nav><!-- must match your namespace & module folder names -->
<active>true</active>
<codePool>local</codePool>
</Custom_Nav>
</modules>
</config>
根据上述情况,应用程序将为您的模块查找配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<!-- app/code/local/Custom/Nav/etc/config.xml -->
<config>
<global>
<blocks>
<catalog>
<rewrite>
<navigation>Custom_Nav_Block_Rewrite_Navigation</navigation>
</rewrite>
</catalog>
</blocks>
</global>
</config>
这样做是在块创建工厂方法中重写类名。目录导航块添加到catalog.xml 布局更新 XML (<block type="catalog/navigation" .../>)。上面的 xpath 会导致类名映射到Custom_Nav_Block_Rewrite_Navigation,而不是通常的Mage_Catalog_Block_Navigation,而正是这个类将被实例化。
最后一步是创建类定义,为了可维护性和遵守 DRY,从原始类扩展:
<?php
/* app/code/local/Custom/Nav/Block/Rewrite/Navigation.php */
class Custom_Nav_Block_Rewrite_Navigation extends Mage_Catalog_Block_Navigation
{
//custom method overrides & additions belong here
}
清除 config 和 block_html 缓存,更改应该可见。要验证,请通过管理面板启用模板路径提示 + 块类名称,或在站点根目录中创建一个简单的脚本:
<?php
/* test.php in Magento root folder */
ini_set('display_errors',true);
include 'app/Mage.php';
Mage::setIsDeveloperMode(true);
Mage::app();
var_dump(Mage::getConfig()->getBlockClassName('catalog/navigation'));
将浏览器指向http://site.com/test.php,输出应显示重写后的类名。