Overriding Controllers in Magento
How to override controllers in Magento?
To override any controller you need to make changes in two files.
- module/etc/config.xml
- module/controllers/ControllerName.php
Assume, Package is the name of your custom package,
Module is the name of your custom module,
CorePackage is the Package name of core Module that you want to override,
CoreModule is the core Module that you want to override
Changes in config.xml file of your module
Write this to config file of your module.
module/etc/config.xml
<?xml version="1.0"?> <config> <modules> <Package_Module> <version>0.1.0</version> </Package_Module> </modules> <!--overriding controller--> <frontend> <routers> <coreModule> <args> <modules> <Package_Module before="CorePackage_CoreModule">Package_Module</Package_Module> </modules> </args> </coreModule> </routers> </frontend> </config>
Changes in controller file of your module
Write this to controller file of your module.
module/controllers/ControllerName.php
<?php require_once 'CorePackage/CoreModule/controllers/ControllerName.php'; class Package_Module_Controller extends CorePackage_CoreModule_Controller { //your code } ?>
Example to demostrate how to override AccountController of Customer Module present in core Mage Package
Suppose you want to override AccountController.php of Mage package which is a part of core file in Magento. Of course you can override any controller in core file using this method.
Go to etc/config.xml file of your module and add the following within <frontend> tag.
<?xml version="1.0"?> <config> <modules> <syntaxpage_customer> <version>0.1.0</version> </syntaxpage_customer> </modules> <frontend> <routers> <customer> <args> <modules> <Syntaxpage_Customer before="Mage_Customer">Syntaxpage_Customer</Syntaxpage_Customer> </modules> </args> </customer> </routers> </frontend> </config>
Add the controller that you want to override.
syntaxpage/customer/controllers/AccountController
<?php require_once 'Mage/Customer/controllers/AccountController.php'; class Syntaxpage_Customer_AccountController extends Mage_Customer_AccountController { //your code } ?>