Need help buying now? +48-22-219-5163 +1-917-720-3250
My Cart

Your Cart is Empty

Need help buying now?
+48-22-219-5163 +1-917-720-3250

Events and observers: principle of work

Events and observers: principle of work

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.

The principle is based on 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:

<?php
class Pfay_Test_Model_Observer extends Varien_Event_Observer
{
   public function __construct()
   {
   }
   public function saveCmsPageObserve($observer)
   {
         $event = $observer->getEvent();
         $model = $event->getPage();
     print_r($model->getData());
         die('test');
 }
}
?>

 

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:

<strong><events>
   <cms_page_prepare_save>
    <observers>
       <Pfay_Example_Model_Observer>
           <type>singleton</type>
           <class>example/observer</class>
           <method> saveCmsPageObserve</method>
           </ Pfay_Example_Model_Observer>
       </observers>
  </cms_page_prepare_save>
</events>
</strong>

 

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. If you have any additional questions please feel free to contact our experts, they will be glad to assist you.

Newsletter