Magento Design Patterns - Principles of Events and Observers

Today we will review such method of modification of basic Magento ® functionality as “design pattern”. This method is considered as a standard one and it is necessary to understand it in order to work with the system successfully.

Principles of Magento Design Patterns

The principle is based on the creation of a module using so-called ‘event’ and ‘observer’ files. The ‘event’ suggests an action which leads to modifications in the store, e.g. when a user presses ‘Checkout’ button. ‘Observer’ monitors the changes and then passes them to the system to make it perform specific actions in a certain order.

In order to create a file Observer.php it is necessary to go to /app/code/local/Pfay/Test/Model/ and insert the following code:

class Pfay_Test_Model_Observer extends Varien_Event_Observer
   public function __construct()
   public function saveCmsPageObserve($observer)
         $event = $observer->getEvent();
         $model = $event->getPage();



This observer is created with ‘SaveCmsPageObserve’ function due to which the events will be fixed after a CMS page is saved on Magento ® backend.

As you can see, this file will monitor the events using ‘getEvent’ method that will send all the modified parameters automatically.

In order to make the observer work properly, it is necessary to inform the system about its existence. Go to /app/code/local/Pfay/Test/etc/config.xml and edit the file config.xml. Add the following code:

           <method> saveCmsPageObserve</method>
           </ Pfay_Example_Model_Observer>



The part of code <strong> <cms_page_prepare_save> </strong> represents a controlled event in this example. In order to launch saveCmsPageObserve, the observer should wait for the action cms_page_prepare_save to start.

The process of completing the task in Observer is controlled by dispatchEvent which generates events. It is located in \core\Mage\Adminhtml\controllers\Cms\PageController.php and should look like this:

Mage::dispatchEvent('cms_page_prepare_save', array('page' => $model, 'request' => $this->getRequest()));

It is possible to create separate files ‘Event’ and ‘Observer’ for each group of actions or processes in Magento ®.

Contact us
Fill in the data using social media accounts
Thank you!
We will contact you shortly

Popular Posts

Join 5,246 Magento-obsessed readers in our mailing list