alias.io

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

honeypot@alias.io 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.

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.

<?php

class [Namespace]_[ModuleName]_Model_Observer extends Mage_Core_Model_Abstract
{
  public function controllerActionPredispatch(Varien_Event_Observer $observer)
  {
    exit($observer['controller_action']->getFullActionName());
  }
}

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"?>
<config>
  <modules>
    <[Namespace]_[ModuleName]>
      <version>1.0.0</version>
    </[Namespace]_[ModuleName]>
  </modules>
  <global>
    <models>
      <[model_group_name]>
        <class>[Namespace]_[ModuleName]_Model</class>
      </[model_group_name]>
    </models>
    <!-- Start -->
    <events>
      <controller_action_predispatch> <!-- The name of the Event -->
        <observers>
          <[namespace]_[modulename]_controller_action_predispatch> <!-- A unique ID -->
            <class>[Namespace]_[ModuleName]_Model_Observer</class>
            <method>controllerActionPredispatch</method>
          </[namespace]_[modulename]_controller_action_predispatch>
        </observers>
      </controller_action_predispatch>
    </events>
    <!-- End -->
  </global>
</config>

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