Rewrite a native magento controller tutorial

I'm working on the translations...the english subtitles will be available soon...
This happens from time to time and it is sometimes not easy to understand how to do it. It differs from the other rewrites but here is the tutorial on how to change the behavior of a native magento controller. In our example we will see how to rewrite the action CartController.

1- Import the class of the old controller

The first step is to create a new controller and import whatever you want to rewrite.

   require_once "Mage/Checkout/controllers/CartController.php";
This gives you something like:

require_once "Mage/Checkout/controllers/CartController.php";
class Pfay_Checkout_CartController extends Mage_Checkout_CartController
    # rewrite of indexAction
    public function indexAction() {
        die('your module has been loaded !!');

The require_once is important if you want it to work (in fact magento can not autoload the class of the rewrited controller)

2- Declare the rewrite of your controller with "before"

This way your class is taken into account instead of CartController native magento, look in the config.xml of your module and insert the following router in frontend

             <Pfay_Checkout before="Mage_Checkout">Pfay_Checkout</Pfay_Checkout>

Yes this is (just) it and it works !! In fact we just told magento to take the controller module of Pfay_Checkout before the Mage_Checkout ones. SO it loads our new class, then this class extends the previous thanks to its require_once ... this way you don't have to copy all the file to modify it and it still use the others native actions :) You shloud notice the "before=" and the fact the router is called himself <checkout> as in the native declaration of the router in the core module. (be carefull if you want to override another class, first have a look in the core to get the good router declaration in the config.xml of the module you want to override). Now you know now how to rewrite a native magento controller, Congratulations! :) If it doesn't work, as usual you can download the code to compare it with yours and see what you've missed.
Available documents for this article :
Questions about this lesson
No questions for this lesson. Be the first !

You must be logged in to ask for help on a lesson.