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 the same way as Magento 1. If you ever used that in Magneto 1, you will not face any problem understanding this for Magento 2.

The events and observers implementation in Magento 2 is based on the publish-subscribe pattern. Therefore, 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 is a messaging pattern where the senders of the 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.

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

Magento 2 Events

Events are dispatched by modules when specific 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 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 the Event and Observer in Magento 2

Let’s start by creating a simple module where we will change the product name on the 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 an events.xml file to catch the 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 a file under etc/adminhtml folder

Frontend area:- Create a file under etc/frontend folder

Global area:- If you want to use Observer in both the Admin area and Frontend area, then create a 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 an 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 to the catalog_controller_product_view event.

There are name and instance attributes in the <observer> element. The name attribute defines the Observer Name that must be unique for each event. 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 an Observer file to catch the 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 observers 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 the ‘checkout_cart_product_add_after’ event and will set a custom price of the product in Magento 2 when adding a product to the cart. Again, we will do this in the same manner. (We are skipping the creation of module.xml and registration.xml files, as discussed above and in our other blog articles).

Step 1: First, create an events.xml file in the 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 the product to 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 folderCreate 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 examples, we learn that there are two important things.

  1. The events which are triggered on some event when we add a product to the cart or when we view a product. So the 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 the general behavior or change in the business logic of the store is executed whenever a specific event for which they were set to listen is triggered. Observers are created in <vendor>/<module>/Observer.