Technology

Custom events in Magento

Posted by Pixafy Team

manny-etienne-gct

This year, I’ve been working extensively in Magento, which is a change of pace from the custom-coded, “from the ground up” projects I’d been doing previously. I was excited about entering this “brave new world” because with my background, I felt I could take quickly to find ways to extend Magento’s core functionality.  One example that was brought to my attention was custom events.

Events in Magento are similar to hooks in WordPress,  which is where code is able to be run during particular ‘hooks’ in the loading process (ie: initialization). In Magento, you can dispatch events whenever you like. For example, in line 335 of Magento’s core customer account controller (app/code/core/Mage/Customer/controllers/AccountController.php), you see this:

Mage::dispatchEvent('customer_register_success', array('account_controller' => $this, 'customer' => $customer)  );

The code is dispatching the ‘customer_register_success’ event, passing in the class object as well as the customer that was just created. From there, any module in Magento that is looking out for this event will execute their designated function. Events are set in the etc/config.xml file of a given module. Following with the example above, if our module “Foo” wanted to run some code when a customer is created, it would look something like this:

<events>

                <customer_register_success>

                    <observers>

                        <foo_update_customer>

                                <type>singleton</type>

                                <class>foo/observer</class>

                                <method>updateCustomer</method>

                                </ foo_update_customer >                           

 </observers>

                </customer_register_success>

      </events>

To summarize, when a customer is created, the function updateCustomer located in the Observer.php of our Foo module will run, having access to the account controller object as well as the customer who was just created.

Knowing this, what we can do now is create our own custom events that can be dispatched as well. For instance, if a certain action occurred in one of the controllers in our module Foo, we can dispatch a custom event:

//Action above is completed, fire off event

Mage::dispatchEvent(‘my_custom_event', array('some_data' => $someData)  );           

And from there, any modules listening for ‘my_custom_event’ will execute their designated function, which is pretty neat.

What are some ways you find are helpful for extending Magento?  Share with us in the comments!