Magento Event Observer Pattern

Magento Event Observer Pattern

Magento has gained emerging popularity in e-commerce development from developer perspective by providing well-implemented design pattern architecture ranging from MVC, Factory, to Event Observer pattern.

Magento Event Observer Pattern

Today we will wade through such pattern Event Observer Pattern. As we know, we can extend Magento core functionality by overriding core classes. By using event observer pattern, we can hook our customization without overriding core classes. It allows developers to inject custom logic or alter the normal workflow of particular functions in the system. That is the power of the event observer pattern. We will see components of observer pattern, when to use, and how to implement this pattern in a custom Magento module.

Need of Event Observer Pattern:

Let’s take one case study to simplify the understanding of event observer pattern. Suppose in our system we have implemented the function whose task is to handle all the business logic of customer registration. Whenever new customer is entered into the site

Send a welcome email to customer
– Verify the customer’s data and update the database
– Subscribe the customer to newsletter chain

After several days, requirements are changed so much that we need to add logic such as whenever new customer is entered in the system, offer them a coupon to get some discounts on particular products. We have altered our function and set.

System works well until now. One day our sales departments changes the ideas and tell us to remove the coupon logic and add some different promotional logic into the system.

Are all these requirements final? Will it be forever?

Certainly not. As we know in the current century, things will never be the same as now. Our system requirements always change.

Thus, every time we need to alter our core classes function or need to extend the models and rewrite it.

Instead of overriding the whole class again and again, it’s a good idea to bind our business logic with some events like whenever some events happen say customer log in, customer place order, a particular function is called. Here’s where event observer pattern comes into the picture.

Introduction of Event Observer Pattern:

As per Wikipedia

Magento Event Observer Pattern-Introduction

The basic idea behind event observer pattern is to decouple the code by excluding modules dependency. When one object changes state, all other objects depending on it will be notified and take appropriate action. The observer then takes responsibility to monitoring the object state. Let’s see how we can use event observer pattern in Magento.

Implementation of Event Observer Pattern in Magento:

There are mainly three terms we need to understand are Events,Event Observer and Event Observer function.

Events:

Event is one kind of trigger that tells system to execute something based on its type. In Magento Event is fired using dispatcherEvent function.

<?php
Mage::dispatchEvent('Before_order_place',array('order_item'=>$modeldata));
?>

This function accepts two parameters, first parameter is unique name of event and second parameter is array type in which we can pass our model data or any other extra attribute which we want to proceed during event execution.

Event Observer:

Event Observer is an event listener. It is observing events in the system. We first need to register our event observer before dispatching any event.

Syntax for registering observer should be same as below in the module config.xml file.

<global>
<events>
<event_name_node>
<observers>
<observer_name_node>
<class>Observer_class_name</class>
<method>methodname</method>
</observer_name_node>
</observers>
</event_name_node>
</events>
</global>

All event related information resides under <events> tag. The <event_name_node> is the event identifier. Note that event identifier needs to pass while dispatching event. Under the <observers> tag <observer_name_node> is a custom identifier for our observer. Best practice is to make it unique by combining package and module name so it won’t conflict with other modules observer. Under that we need to specify three nodes are <class>,<method> and <type>. <class> node is referred to observer class. <method> node referred to observer function. This function is executed when event is fired. <type> node is optional and could be singleton or model.

Note:

We can place <events> node under <global>,<frontend> or <adminhtml> tag.

If you want to process your event only when something happens at front-side, place it under <frontend>.

If you want to process your event only when something happens at backend-side (admin-side) place it under adminhtml.

If there is no such restriction you want to apply place it under <global>.

Event Observer Function:

Event observer function is a normal Magento model function that is executed when system fires an event. Generally, this function defines in Observer.php model file.

<?php
public function beforeOrderPlace($observer)
{
$orderitem= $observer->getEvent()->getOrder();
}
?>

Here you can see parameter $observer. It holds event related data.

We are done with the basic of Magento Event Observer Pattern, now it’s time to create a custom event in our custom Magento module.

Custom Event in Custom Magento Module:

As a Magento developer, we frequently create our own custom module whenever we want to hook some extra bit of code in normal flow. Sometimes we create a module which is working separately from Magento internal flow (which do not affect core models) and sometimes we may want to alter the Magento internal flow, say you want to change in normal execution of customer login or say order processing flow.

In those cases, there are two approaches to achieve our goal. First is to override the core classes in our module and rewrite the functions in which we want modifications. Second, one is using event observer pattern.

When our module is going to deal with specific actions like order place before and after, customer registration before and after, item add to cart before and after etc. then second approach is very handy without overriding the core classes and making our code less complex.

Recently I had to deal with the custom event in my custom module to manipulate the user input data along with saving it to database. How have I achieved this? Let’s see by using the actual scenario.

Actually, the scenario is whenever a customer submits a form from frontend we need to identify that either it’s a registered customer or guest. Based on their identity we need to send them an email and subscribe them to particular newsletter chain. After doing all this we need to save data in to database.

We can write this whole logic into a single function. However, what we can do is decouple the database operation and email sending logic by leveraging Event observer pattern.

First step is to create event observer. To create event observer write following code in to module’s `config.xml` file.

<global>
..
..
<events>
<email_send_event>
<observers>
<readmyviews_customevent_observer>
<type>singleton</type>
<class>customevent/observer</class>
<method>sendcustomemail</method>
</readmyviews_customevent_observer>
</observers>
</email_send_event>
</events>
..
..
</global>

Here we have defined event email_send_event under event tag. By using this event name we will dispatch our event.

Under <observers> tag we have declared our class name in which our observer function resides. In our case class is Readmyviews_Customevent_Model_Observer and observer method is Sendcustomemail.

Moving one step further let’s create observer function inside observer.php file which is located under the module’s model directory.

In observer.php enter following code

<?php
class Readmyviews_Customevent_Model_Observer
{
public function Sendcustomemail($observer) {
$event = $observer->getEvent();
$customer= $event->getCustomerType();
// newsletter subscription logic goes here
}
}
?>

In our observer function by using $observer object we have fetched observer data which is passed by dispatcher function.

Dispatch Custom Event:

The last step is to dispatch our custom event using dispatcher code. Write the following code in your controller’s method.

<?php
$modeldata = array('customer_type'=>'guest');
Mage::dispatchEvent('email_send_event',$modeldata);
//save data code goes here
?>

Here in our dispatcher we have specified first argument is the name of our event and second argument is model data array. As we have seen in our observer function we can access this argument by a getter method.

As per requirements, you can fire events from any other file. In our case, we have fired it from controller.

That’s it. We have completed the basics of Magento event observer pattern and how to implement a custom event in our model. I hope by referring to this article you are able to write your own custom module with custom event observer. Feel free to ask any questions in the section below.

Would you like to  crawl your website with best result in google. Please check out the great  article on SEO CHECKLIST.

One thought on “Magento Event Observer Pattern

  1. Thanks chirag.

    Enjoyed a lot while reading. you did provide a right way to make the custom code in Magento. It will help me a lot in future. Please share this kind of amazing article. W

    Waiting for your next article.

Leave a Reply