How to use events and observers in Magento 2

How to use events and observers in Magento 2

Events and observers are one of the main ways to extend Magento’s core functionality. Magento 2 provides the events and observers customization options same as Magento 1. If you ever used that in Magneto 1 you will not face problem to understand this for Magento 2.

The events and observers implementation in Magento 2 is based on the publish-subscribe pattern. You can run your custom code in response to a specific Magento event using events and observers.

 

You can also create your custom event.

 

Publish-Subscribe pattern

The publish-subscribe pattern messaging pattern where senders of messages (publishers), do not program the messages to be sent directly to specific receivers (subscribers). Instead, the programmer “publishes” messages (events), without any knowledge of any subscribers there may be.

Similarly, subscribers’ express interest in one or more events, and only receive messages that are of interest, without any knowledge of any publishers.

 

Magento 2 Events

Events are dispatched by modules when certain actions are triggered. In addition to its own events, Magento allows you to create your own events that can be dispatched in your code.

Dispatching events:

You can dispatch Magento 2 Events using the “Magento\Framework\Event\Manager” class.

To dispatch an event, you have to call the dispatch function of the event manager class, providing the name of the event along with an array of data that you wish to deliver to observers.

 

Magento 2 Observers

Observers are the particular classes that control the general behavior or change in the business logic of the store. They are executed whenever a specific event for which they were set to listen is triggered.

To create an observer in Magento 2, you must place your class file under the ModuleRoot/Observer directory. The observer class file should use Magento\Framework\Event\Observer and Magento\Framework\Event\ObserverInterface class and define the executive function.

 

How to Use Event and Observer in Magento 2

Let’s start by creating a simple module where we are going to change product name when we go on product view page. We will do this by making a separate module.

 

Step 1: Create registration.php in app/code/Bizspice/Eventexample directory

 

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
     ‘Bizspice_Eventexample’,
     __DIR__
 );

 

Step 2: Now, create a module.xml file in the app/code/Bizspice/Eventexample/etc

 

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Bizspice_Eventexample" setup_version="1.0.0"/>
</config> 

 

Step 3: Create events.xml file to catch event

Magento 2 uses Area Definition to manage the store files. It provides three different areas to create configuration files for the events

 

Admin area :- Create file under etc/adminhtml folder

Frontend area :-

Create file under etc/frontend folder

Global area :- If you want to use Observer in both Admin area and Frontend area ,then create file under

etc/ folder

In this example, since I want to make changes to the Product Name displayed in the product view, I will use the frontend area.

Create events.xml file in Bizspice/Eventexample/etc/frontend directory and add the following code.

 

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="catalog_controller_product_view">
        <observer name="showproductdata" instance="Bizspice\Eventexample\Observer\Product\Change" />
    </event> 
</config> 

The above XML code is listening for the catalog_controller_product_view event.

There are name and instance attributes are in the <observer> element. The name attribute defines the Observer Name that must be unique for each event, and the instance attribute defines the specific Magento 2 class that needs to be executed when the catalog_controller_product_view event is dispatched.

 

Step 4: Create Observer file to catch event. Create Change.php in app/code/Bizspice/Eventexample/Product/Observer folder.

 

namespace Bizspice\Eventexample\Product\Observer;
class Change implements \Magento\Framework\Event\ObserverInterface 
{
   public function execute(Magento\Framework\Event\Observer $observer) {
      $product = $observer->getProduct();
      $originalName = $product->getName();
      $modifiedName = $originalName . ' - Modified Name';
      $product->setName($modifiedName);
   } 
} 

That’s it we are done with observer and events. But we will take another example to make it clearer to you.

 

Another Example:-

So Now let’s take a second example where we are using ‘checkout_cart_product_add_after’ event and will set custom price of product in magento2 when adding product to cart. We will do this in the same manner. (We are skipping of creation of module.xml and registration.xml file as we have already discussed in the above section and many of our blog articles).

 

Step 1 : First create events.xml file in folder

 

<Namespace>/<Module>/etc/frontend’ and use event ‘checkout_cart_product_add_after’. Here ‘checkout_cart_product_add_after’ is magneto 2 core event which fires after we add product in cart

 

Create Bizspice\Customprice\etc\frontend\events.xml

 

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
   <event name="checkout_cart_product_add_after">
       <observer name="customprice" instance="Bizspice\Customprice\Observer\CustomPrice" />
   </event>
</config> 

 

Step 2 : Now create CustomPrice.php file in Observer folder

 

Create Bizspice/Customprice/Observer/CustomPrice.php

 

<?php namespace Bizspice\Customprice\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magneto\Framework\App\RequestInterface;
class CustomPrice implements ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer) {
      $item = $observer->getEvent()->getData('quote_item'); $item = ( $item->getParentItem() ? $item->getParentItem() : $item );
      $price = 100; //set your price here $item->setCustomPrice($price); 
      $item->setOriginalCustomPrice($price);
      $item->getProduct()->setIsSuperMode(true);
    } 
} 

 

Summary

So, from both example we get to know that there are two important things.

 

  1. The event which are triggered on some event when we add a product to cart, or when we view a product . So First important thing is to identify the correct event on which we want to Modify certain behavior of magneto. In the above examples catalog_controller_product_view and checkout_cart_product_add_after are the events . and we define them in event.xml

  2. The observer is where general behavior or change in the business logic of the store are executed whenever a specific event for which they were set to listen is triggered.observer are created in <vendor>/<module>/Observer.