Saturday , October 21 2017
Home >> All tutorial >> Magento Developers’ Guide – Part 11: Events and Observers in Magento

Magento Developers’ Guide – Part 11: Events and Observers in Magento

1. Theory

Event: 
We can consider an event as a kind of flag that rises when a specific situation happens for example when the user presses the « pay » button of your website, it is an event. Your order has been registered? Here it is an event too. You can read more about Events in Magento here.

Observer: 
An Observer is also called « Listener » he will listen to your program to detect events. When there is an event taking place, Observer in Magento will perform an action.

2. Create an Observer

An Observer in magento is in the directory Model of your plugin and extends the class Varien_Event_Observer (class which I think is clear …), go in /app/code/local/Pfay/Test/Model/ folder and create your Observer.php

  1. <?php
  2. class Pfay_Test_Model_Observer extends Varien_Event_Observer
  3. {
  4.    public function __construct()
  5.    {
  6.    }
  7.    public function saveCmsPageObserve($observer)
  8.    {
  9.          $event = $observer->getEvent();
  10.          $model = $event->getPage();
  11.      print_r($model->getData());
  12.          die(‘test’);
  13.  }
  14. }
  15. ?>

Here we’ve created an Observer with a function saveCmsPageObserve , this function is the method that will be executed when a page CMS will be saved in the backend of Magento.

In our example we stops the program to display a message but instead of a true die(), you will create a process to record additional information on your page in another table (for exemple)

3. Ensures that the Observer is declared in Magento

Now we have created our Observer , we need to declare it in Magento, how it’s done?

We will edit the config.xml our plugin. So open the file:/app/code/local/Pfay/Test/etc/config.xml
And in , after or after add:

  1. <strong><events>
  2.    <cms_page_prepare_save>
  3.     <observers>
  4.        <Pfay_Exemple_Model_Observer>
  5.            <type>singleton</type>
  6.            <class>exemple/observer</class>
  7.            <method> saveCmsPageObserve</method>
  8.            </ Pfay_Exemple_Model_Observer>
  9.        </observers>
  10.   </cms_page_prepare_save>
  11. </events>
  12. </strong>
Tutorial by: pierrefay.com
 

You are preparing for Magento exam? don’t miss this special FREE Magento Ebook magento certification study guidehttp://www.magestore.com/magento-certification-study-guides.html

We also contribute great content of Magento Tutorial for Magento 1.x.

DON'T MISS THE CHANCE!

magento tutorial

About Champ

Leave a Reply

Your email address will not be published. Required fields are marked *

Heap | Mobile and Web Analytics