
MAGENTO 1.X – HOW TO CREATE AN OBSERVER FROM SCRATCH
In some cases, you would need to add some custom functionality inside Magento flow, for those ones, Magento provide several events where you can insert your custom code in a custom extension. To do so, you need to perform the following steps:
- Create a new module xml file at app/etc/modules/Vendor_ObserverTestExt.xml
123456789<?xml version="1.0"?><config><modules><Vendor_ObserverTestExt><active>true</active><codePool>local</codePool></Vendor_ObserverTestExt></modules></config> - Create the following folder structure for your module:
app/code/local/Vendor/ObserverTestExt/
app/code/local/Vendor/ObserverTestExt/etc/
app/code/local/Vendor/ObserverTestExt/Model/ - Create your module configuration file:
On folder app/code/local/Vendor/ObserverTestExt/etc create a config.xml file with the following content:
1234567891011121314151617181920212223242526<?xml version="1.0"?><config><modules><Vendor_ObserverTestExt><version>0.0.1</version></Vendor_ObserverTestExt></modules><global><models><callobservertestext><class>Vendor_ObserverTestExt_Model</class></callobservertestext></models><events><sales_order_place_after><observers><vendor_observertestext_model_observer><type>singleton</type><class>Vendor_ObserverTestExt_Model_Observer</class><method>myObserverMethod</method></vendor_observertestext_model_observer></observers></sales_order_place_after></events></global></config>
Notes:
<callobservertestext> is a unique identifier of our observer’s folder, inside it, the tag <class> represents our observer folder, and the prefix of our observer class.<events> Here we are going to set up each event where we want to call a custom method (eg: sales_order_place_after). A nice cheat of all events is this one: https://www.nicksays.co.uk/magento-events-cheat-sheet-1-9/
<vendor_observertestext_model_observer> This is a unique identifier of our observer, it’s very common to use the observer class name.
Inside it, the <class> tag can be set as two different ways:
* Class name: Vendor_ObserverTestExt_Model_Observer.
* folderidentifier/filename: callobservertestext/observer. - Create the Observer.php file inside app/code/local/Vendor/ObserverTestExt/Model with the following content:
123456789101112131415161718192021<?php/*** Created by PhpStorm.* User: amper* Date: 12/02/17* Time: 23:29*/class Vendor_ObserverTestExt_Model_Observer {public function myObserverMethod($observer) {//$observer contains data passed from when the event was triggered.//You can use this data to manipulate the order data before it's saved.//Uncomment the line below to log what is contained here://Mage::log($observer);Mage::log('We have just made an Observer!');}}?>
- Finally, lets clean cache, make a complete purchase order(just for this example, and to raise the extended event) and check out your log file in var/log.