博客

Magento 二次开发系列十四 — 控制层如何重写(补充篇)

【php教程】Magento 二次开发系列十四 — 控制层如何重写(补充篇)

本节是对系列十二节的补充,也可以认为是独立的章节,主要介绍控制层的重写。

通过前面章节的学习,我们应该掌握了Model,Block等核心代码的重写,但是没有controllers控制层的重写,所以单独增加一个章节来阐述,也是为了这个教程系列的一个全面收尾。

1.新建文件目录app/code/local/App/Shopping,这个是用重写购物车的控制层,因为我们想要修改前台方法,本着遵守不修改核心代码的原则,我们重写它;

2.新建子目录Shopping/controllers,目录下新建文件CartController.php,代码如下:

require_once ‘Mage/Checkout/controllers/CartController.php’;//引入core中的原控制层,然后下面继承它
class App_Shopping_CartController extends Mage_Checkout_CartController {

function indexAction(){
parent::indexAction();

}

function _initProduct() {
$productId = ( int ) $this->getRequest ()->getParam ( ‘product’ );
$compatibelModel = $this->getRequest ()->getParam ( ‘compatible_model’ ); // 这是我们要修改的逻辑
if ($productId) {
$product = Mage::getModel ( ‘catalog/product’ )->setStoreId ( Mage::app ()->getStore ()->getId () )->load ( $productId );
$product->setData ( ‘compatible_model’, $compatibelModel );
if ($product->getId ()) {
return $product;
}
}
return false;
}
}

2.新建子目录Shopping/etc,目录下新建文件config.xml,代码如下

<?xml version=”1.0″?>
<config>
<modules>
<App_Shopping>
<version>0.1.0</version>
</App_Shopping>
</modules>
<global>
<!– This rewrite rule could be added to the database instead –>
<rewrite>
<!– This is an identifier for your rewrite that should be unique –>
<!– THIS IS THE CLASSNAME IN YOUR OWN CONTROLLER –>
<App_Shopping_cart>
<from><![CDATA[#^/checkout/cart/#]]></from>
<!–
- Shopping module matches the router frontname below – checkout_cart
matches the path to your controller Considering the router below,
“/shopping/cart/” will be “translated” to
“/App/Shopping/controllers/CartController.php” (?)
–>
<to>/shopping/cart/</to>
</App_Shopping_cart>
</rewrite>
</global>
<!–
If you want to overload an admin-controller this tag should be <admin>
instead, or <adminhtml> if youre overloading such stuff (?)
–>
<frontend>
<routers>
<App_Shopping>
<!– should be set to “admin” when overloading admin stuff (?) –>
<use>standard</use>
<args>
<module>App_Shopping</module>
<!– This is used when “catching” the rewrite above –>
<frontName>shopping</frontName>
</args>
</App_Shopping>
</routers>
</frontend>
</config>

注意这个配置文件,重写的放在标签rewrite中,还有个正则“#^/checkout/cart/#”,意思是访问这个路径时会转到下面的标签to中的路径,执行它的逻辑,从而达到重写的目的;

3.既然是个新模块,我们就要添加下系统的模块配置,新建文件/app/etc/modules/App_Shopping.xml,代码如下:

<?xml version=”1.0″?>
<config>
<modules>
<App_Shopping>
<active>true</active>
<codePool>local</codePool>
</App_Shopping>
</modules>
</config>

至此,重写控制层的工作就完成了,是不是很简单。

注:此文为原创,如转载请注明出处。