Magento customize methods (events)

Magento
There two main ways with magento code can be customized, using events, and overriding classes. In this article it will be described in more details using events method. Magento is written in OOP manner and implements "observer pattern". So this mean that in key point of application magento has events and make dispatch of this events. This allows us to inject code in magento normal workflow, and change defauult behavior.
Events customization method has advanced that can be used for multiple times and with other customized code (extension), without risk to appear conflicts in another module or extension that override same piece of code(extension/module) like your code(extension/module) but it has disadvantage to not be able to change magento logic/workflow completely.
Let's take an example:
Magento after each order that was placed by an customer dispatch event: "sales_order_place_after", and give us in this event order data.
    Mage:dispatchEvent('sales_order_place_after', array('order'=>$this));
If we want that after each order to send an email to site admin, with some order data, we can build an observer class that listen event "sales_order_place_after".
After that we tell magento that new observer exist by a little piece of xml code like bellow, in module config.xml file.
    <events>
        <sales_order_place_after>
            <observers>
                <Namespace_MyModule>
                    <type>singleton</type>
                    <class>Namespace_MyModule_Model_Observer</class>    
                    <method>onOrderPlaceSendMail</method>
                </Namespace_MyModule>
            </observers>
        </sales_order_place_after>
    </events>
In the end all we need to do is to create method onOrderPlaceSendMail in class Namespace_MyModule_Model_Observer that send mail if an order is placed.
Add comment
 
 
 

Comments