How to extend Magento core controller?

Hi, today I’ll show you how to edit Magento’s core module without messing with core files themselves, or “the right way of doing things”. 😀

First of all, I chose Magento’s Customer module and its Account controller as an example. First, you need to find it in Magento’s Core folder (full path: “app/code/core/Mage/Customer/controllers/AccountController.php“).

First step is to create and place folders in your module that will override Magento’s core controller. On to that part:

  1. First, create this file in same folder structure: app/code/local/Inchoo/Coreextended/controllers/Frontend/Customer/AccountController.php. (of course, you can always replace Inchoo with desired namespace, and Coreextended with some other module name, but you’ll need to edit the rest accordingly).
  2. Then create xml for our module located here: app/code/local/Inchoo/Coreextended/etc/config.xml (same analogy as above applies)
  3. And finally, create this file app/etc/modules/Inchoo_Coreextended.xml.

Second step is to enter the data inside them:

1. The AccountController.php’s content:

< ?php
require_once Mage::getModuleDir('controllers', 'Mage_Customer').DS.'AccountController.php';
//we need to add this one since Magento wont recognize it automatically
 
class Inchoo_Coreextended_Frontend_Customer_AccountController
extends Mage_Customer_AccountController
{//here, you extended the core controller with our
 
public function indexAction()
{
parent::indexAction();
//you can always use default functionality
}
 
public function myactionAction()
{
//my code
//you can write your own methods / actions
}
 
public function mymethod()
{
//my code
//you can write your own methods
}
 
public function loginAction()
{
//finally you can write your code that will rewrite the whole core method
//and you can call for your own methods, as you have full control over core controller
}
}

2. The config xml content:

<!--?xml version="1.0"?-->
 
 
 
0.2.0
 
 
 
 
 
 
 
Inchoo_Coreextended_Frontend_Customer

3. And finally Inchoo_Coreextended.xml source:

< ?xml version="1.0"?>
<!--we need to enable this module as any other if-->
<!--you wish to do it as standalone module extension-->
 
 
 
true
local

And there you go. In this 3 steps (or 6 if you count the creation of files), you created an extension of Magento’s core controller. As I heard and same as I read, this is considered the best practice of extending Magento’s core controllers. It’s immune to upgrading as long as Magento (Varien) don’t change something drastically in their core files.

And that’s about it. I hope this helped someone. Bye!

Edit: special thanks to couple of colleagues here at Inchoo who pointed to me that my first version of config.xml wasn’t configured right. I rewrote this part of article. Also, thanks to all of you who commented article with some strong points. 😀