Using Observers to Modify Magento
Using observers is really quite simple. Let's jump in and see an example of setting up an observer.
Our simple observer will process additional information when a customer submits an order. I recently used this type of observer to add a "source" field on an order.
Identify the event and necessary parameters
First, we will need to identify the event that will trigger our observer. In our case, the event name is sales_order_place_before. We found this observer in the dispatchEvent function in app/code/core/Mage/Sales/Model/Order.php. Typically, we'll only need to find the event in the Magento core code, this is just to reference what the event will be passing.
The dispatchEvent function takes 2 parameters. First, the name of the event as we are defining it. Second, an array of objects or values to pass to the observer. In our case, the order object is passed as "order".
Mage::dispatchEvent('sales_order_place_before', array('order'=>$this));
Build the function
Next, we'll write the code.
class Irps_ModuleExample_Model_Observer{ public function processOrder(Varien_Event_Observer $observer){ $order = $observer->getEvent()->getOrder(); //extract the order object that was passed from the event $order->setSourceCode('some source code'); return $this; } }
Configure Magento to use the observer
The only thing left to do now is to tell Magento that we are listening for an event and that we want to run our new function when we see it.
app/code/local/Irps/ModuleExample/etc/config.xml:
<global> <events> <sales_order_place_before> <observers> <irps_moduleexample> <class>Irps_ModuleExample_Model_Observer</class> <method>processOrder</method> </irps_moduleexample> </observers> </sales_order_place_before> </events> </global>
Note: This is not all of the config.xml file
That's it! We've identified the event we want to listen for. We've created our custom function that we want to execute when the event occurs. And, we've configured Magento to allow us to handle the event.
I have used observers many times to modify functionality in Magento and it is, by far, the most friendly method when you upgrade Magento. Of course, you will still want to test all of your functionality before pushing out an upgrade.
Share with us some of the ways that you have used observers in the comments.