I'm Elbert, a Dutch expatriate programmer in Australia. I use and create open-source software.

Currently employed as Technical Director at Tundra Interactive, a digital agency in Melbourne.

Contact PGP Key

Creating a Magento module, part III

Published on November 11, 2012

Continued from Creating a Magento module, part II (Model).

This article describes how to create an Event Observer.


Perhaps the simplest form of a Magento Model is an Event Observer. Events are dispatched throughout Magento's code, allowing Observers to introduce code in decoupled way.

1. Create an Observer

In this example the Observer will listen for the controller_action_predispatch Event. This Event is emitted right before a page is loaded.

Create a file at app/code/local/[Namespace]/[ModuleName]/Model/Observer.php.


class [Namespace]_[ModuleName]_Model_Observer extends Mage_Core_Model_Abstract
  public function controllerActionPredispatch(Varien_Event_Observer $observer)

2. Configure the Observer

Open app/code/local/[Namespace]/[ModuleName]/etc/config.xml and add the section between Start and End. Substitute the values between square brackets with your own.

<?xml version="1.0"?>
    <!-- Start -->
      <controller_action_predispatch> <!-- The name of the Event -->
          <[namespace]_[modulename]_controller_action_predispatch> <!-- A unique ID -->
    <!-- End -->

The above configuration instructs Magento to call the controllerActionPredispatch() method on the Observer Model when the Event is dispatched.

Observers can listen for multiple Events using different methods. Likewise multiple Observers can listen to a single Event.

3. Test the Observer

Navigating to the home page of your Magento installation should show a blank page with the string cms_index_index, the full action name.

In a UNIX-like environment you can use grep to get a list of all Events in Magento:

$ grep dispatchEvent app/code -R