Implementing observer on Magento module

Posted on Category:Magento

This post describes the steps necessary for creating an Magento Observer

First, if you’re creating a new module, be sure you have defined your module in app/etc/modules directory:

<?xml version="1.0"?>
<config>
    <modules>
        <Namespace_Modulename>
            <active>true</active>
            <codePool>local</codePool>
        </Namespace_Modulename>
    </modules>
</config>

To define a observer, you must enter it in your module’s config.xml file:

<!-- app/code/local/NameSpaceName/ModuleName/etc/config.xml -->
<config>
    <modules>
        <NameSpaceName_ModuleName>
            <version>0.1.0</version>
        </NameSpaceName_ModuleName>
    </modules>
    <global>
        <models>
            <modulename>
                <class>NameSpaceName_ModuleName_ClassName</class>
            </modulename>
        </models>
        <events>
            <observer_name>
                <observers>
                    <unique_observer_name>
                        <class>modulename/observerdir_observer</class>
                        <method>ObserverMethodName</method>
                    </unique_observer_name>
                </observers>
            </observer_name>     
        </events>

The line:

<class>modulename/observerdir_observer</class>

tells the Magento observer’s class name and location. The observer class shoud look like something like this:

//app/class/local/NamespaceName/ModuleName/observerdir/Observer.php
class NameSpaceName_ModuleName_Model_ObserverDir_Observer
{
 
    public function executeSomeAction(Varien_Event_Observer $observer)
    {
        var_dump($observer->getData('some_data'));
        die ('executing the observer action');
    }
}

The Observer is being called from any action by calling the static method:

Mage::dispatchEvent('observer_name',array('some_data'=>$data));