Magento events and observers

By 4th August 2013January 16th, 2018CMS, Technology & Business Intelligence

If you are familiar with the concept of events in programming, you probably know the benefits of using them. If not – let’s have a few words of introduction.

Wikipedia says: “event-driven programming (EDP) or event-based programming is a programming paradigm in which the flow of the program is determined by events—e.g., sensor outputs or user actions (mouse clicks, key presses) or messages from other programs or threads.”  In brief words – if you perform an action, you can send a message to the whole system about what action was performed (usually together with selected data). This way you just write a piece of code which should be executed after or before the specified action occurs and state what events should trigger the code.

Magento gives you the benefits of using events. If you check app/Mage.php file, you can notice dispatchEvent($name, $data) function. The first parameter is the event name, the second is an array of data related to it. So if in your module you need to notify the system that a given action has just occurred, you just write:

Mage::dispatchEvent(‘my_action’, array(‘foo’ => $bar))

And then you can handle it by creating an observer (of course, there are a lot of core events and you can handle them in your custom observers, too). The observer is a class which listens to all events and responds only to those which it is assigned to. Observers are models and usually do not extend any class. The name pattern for an observer is <Namespace>_<ModuleName>_Model_Observer. If you want to see an example, open app/code/core/Mage/Catalog/Model/Observer.php There are a few functions – all public and with Varien_Event_Observer $observer parameter. Here you can notice how to get the data passed to Mage::dispatchEvent():


where ‘store_id’ is the data array key. So for our previous example it would look like:


Now, how do you assign an observer to an event? It is done in config.xml file of the module to which the observer belongs. Check app/code/core/Mage/Catalog/etc/config.xml At the same level where models and blocks nodes are declared you can see ‘events’ node. Children of this node are all events handled by observers included by the module. Then, inside each event node, there is an ‘observers’ node (you can have multiple children here). The observers node contains a list of observers used by the module and the names given to them is not really important – they should be meaningful to keep the code easy to maintain, but there is no pattern they should follow. Next, the content of each observer: the class and the method, so that Magento will know what method should be executed. And that’s all!