Magento Developper’s Guide (Lesson 11) – Events and Observers in magento

16 novembre 2011

This tutorial is the 11th of many tutorials , you will now learn how to create your own controller in Magento. If you have not read the first articles yet, I strongly advise you to do so.

Today we will see a new way to modify a base behavior of magento thanks to the Events and the Observers. This kind of programming method is a web development standard i recommend you to master if you want to work with Magento.

1 – A bit of theory

This programming method is called a « design pattern », what that is?

First,we will start by defining two terms:

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. Etc …

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

A small example: The neighbor and you

Let us talk a bout a situation , you’re at home and you host a party ! you start the night party and everything goes well, then one time, one of your friend who drank a little too much (Okok he’s completly drunk xD !) begins to sing loudly in the garden

Your neighbor is a « no life » and has never had a friend, he’s at home all the time (worst !! maybe it is a magento developper xD!) And it has nothing to do best of his life waiting you make too much noise to be able to call the police (for disturbing the peace) … that’s how he like to spent his time (we need all kinds of people to make a world).

In short, we all know that kind of situation. Now in this story, a friend makes too much noise, « making too much noise » here is the event .
The observer is your neighbor, and he watches what? If you make too much noise (if an event is raised). And there will be action when the event is raised: call the police!

With this great example (in which I’m not talking about real facts … especially not my neighbor xD), you get the principle i hope! Now let’s go for practice and we will move to our favorite e-commerce CMS Magento …!

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

<?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');
 }
}
?>

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).

I think i do not need you to explain this short code, I get the event using the method getEvent on the Observer we passed as parameter of the method (the parameter is automatically sent to the method). Then starting from the event, from the method getPage(), I get my cmspage and I display its content with print_r and the getData as we are used to.

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? … 11th tutorial, if you have not an idea I urge you to hang you … muahahaha restart this series of tutorials from the beginning because I think you have not understood the Magento development principles.

SO…if you have understood, 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:

<events>
   <cms_page_prepare_save>
	<observers>
	   <Pfay_Exemple_Model_Observer>
	       <type>singleton</type>
	       <class>exemple/observer</class>
	       <method> saveCmsPageObserve</method>
           </ Pfay_Exemple_Model_Observer>
       </observers>
  </cms_page_prepare_save>
</events>

Some small

explanations are necessary here:

Tag:

 <cms_page_prepare_save> 

Represent the event is monitored in our example your neighbor was waiting you to do a lot of noise in order to launch its action (call the cops). Here we expect the action cms_page_prepare_save to launch our action saveCmsPageObserve ).

The rest seems logical:

    <observers>
	  <Pfay_Exemple_Model_Observer>
	 <type>singleton</type>
	 <class>exemple/observer</class>
	 <method> saveCmsPageObserve</method>
         </ Pfay_Exemple_Model_Observer>
    </observers>

We define the class observer that will be used when this method will be called with the type, class and method to use.

Ok Ok I understand but how do we know that it is the event cms_page_prepare_save wich is used?

It is not complicated, in fact we will see in the core file, it opens the file: \app\code\core\Mage\Adminhtml\controllers\Cms\PageController.php look at the method saveAction() , at the following line:

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

It is by dispatchEvent that generates the event in our program.

With this line we know that the event is called cms_page_prepare_save and that he passes a table with a page that contains the model object and an request object, they may be recovered in your observer method thanks to the features getPage() and getRequest() .

« Et voilà ! », I think we went around. Now you can have fun with the events and Observers in Magento.

Leave a comment to please me or to ask a question and if you liked this article help me by sharing a link to this article on your blog, facebook page or twitter.

find the summary of this tutorial

You should read this too :
  • No Related Post
Sam # 18 novembre, 2011

What happened to lesson 10?

# 25 novembre, 2011 Pranay

Nice tut.. like ur example :)

Pierre FAY # 25 novembre, 2011

if i answer to you’re question…i will be obliged to kill you xD

# 25 novembre, 2011 Pierre FAY

thanks..i’ve made it will all my heart :p

Dalton # 5 décembre, 2011

I am froveer indebted to you for this information.

# 6 février, 2012 Roy Vincent

lesson 10 please :(

bhavesh # 7 février, 2012

Nice 1 …..i will try and follow your step

good tut……

# 13 mars, 2012 prat

HI,
It’s really very informative & useful article. I wanted to know more about event-observer model of Magento.
Currently I am focussing on sales order placement event. I have created one custom table in Magento that contains different sales order related columns(like increment id from sales_flat_order, item_name,sku from sales_flat_order_item etc.). I connected to mysql database through PHP. I join these table to form a single query & put this query which fetches & inserts data into custom table.
Now my ultimate aim is once customer places order, this php file must get called so that all data fetched through that query get inserted into custom table…
So how event-observer model I can use for the same…do u have any sample code for the same…
Plz guide me…

Regards,
Prat

raj # 2 août, 2012

I tried to use sales_order_place_after event just did the folder structure specified by you and also added a file at app/etc/modules/foldername_innerfoldername.xml
but still for me when an order is succesfully placed this actions are not happening …………..

My code includes some Mage:: models,singletons so do i need to include mage.php to this page

# 18 décembre, 2012 Kishore

What an awesome explanation of everything you do in an observer. Thanks for the great blog and congrats on being such a great magento developer.

nikunj vadariya # 6 juin, 2013

i like your example…..:)

# 20 septembre, 2013 abhishek kothari

vry nice example neighbour??

Pascal Borkenhagen # 2 octobre, 2013

In the example above, the correct way for the /app/code/local/Pfay/Test/etc/config.xml Line 6 would be:
Pfay_Test_Model_Observer

# 4 novembre, 2013 TienDoan

Hello, first of all I thank you for your great article, according to learn the event (written in the config.xml file) to start the event, the client sends requests to the server, the event occurred sever step in processing the request. You asked me if I copi 1 site link (is that what the event handler) to past into the browser it does not go through the Event?
Thank you much.! Wish you a happy day!

Kunal Mazumder # 18 novembre, 2013

Cool XD!

# 9 décembre, 2013 Katheermizal@gmail.com

Thank you for your best example about observer

taukilali # 20 décembre, 2013

Wow..What a great tutorial. :)

# 11 janvier, 2014 Smitendrasinh

Hi,

Nice tutotial and very nice real life example « The neighbor and you » :) thank you. The real life exmple make it easy to understand.

Once Again Thank you. :)

Vous aussi donnez votre avis
(requis)



Expert magento sur Lille - Pierre FAY