Say I want to override Magento Catalog Product controller, say my namespace is Magex and my module name is Powercat.
Firstly, add the following to Powercat/etc/config.xml. What it does is adding another route “prowercat” in addition to “catalog” to frontend. When http://mydomain/catalog/somecontroller/someaction/ is routered, powercat/somecontroller/someaction will be loaded before (see the attribute “before”?) catalog/somecontroller/someaction. If powercat/somecontroller/someaction is available, people get some page when visiting http://mydomain/catalog/somecontroller/someaction/ or http://mydomain/powercat/somecontroller/someaction/. I will not publish the latter url because the whole point of overriding a controller is reusing the Magento original url.
<?xml version="1.0"?> <config> <frontend> <routers> <catalog> <args> <modules> <anyname before="Mage_Catalog">Magex_Powercat</anyname><!-- the tag name can be any name --> </modules> </args> </catalog> </frontend> </config>
Secondly, create a subclass in the following format. “require_once” is essential because controllers are not auto-loaded.
<?php require_once 'Mage/Catalog/controllers/SomeController.php'; class Magex_Powercat_SomeController extends Mage_Catalog_SomeController { //function someAction here } ?>
Last but not the least, put the overriding controllers into a dedicated module. Otherwise it is very easy to break Magento fallback mechanism. For example, suppose Magex_Powercat has two controllers.
- Magex_Powercat_IndexController does its own logic (not extending Mage_Catalog_IndexController, and
- Magex_Powercat_ProductController extends Mage_Catalog_ProductController
The scenarios are:
- When people visit http://mydomain/catalog/product/someaction/, powercat/somecontroller/someaction will be loaded – OK.
- When people visit http://mydomain/catalog/category/someaction/, catalog/category/someaction will be loaded (because Powercat does not have CategoryController, Magento will fallback to Mage’s CategoryController) – OK.
- When people visit http://mydomain/catalog/index/someaction/, if Powercat’s IndexController does not have someAction (only Mage’s IndexController has) – Error happens!
- When people visit http://mydomain/catalog/index/someaction/, if Powercat’s IndexController does have someAction, page will load without error. However, remember Magex_Powercat_IndexController does its own logic? No router to the original logic!