How To Use Magento 2 Events and Observers

Magento 2 Events

Events are dispatched by Magento 2 Modules whenever specific actions are triggered. When an event dispatches, it passes data to the observer that is configured to watch (or monitor) that event. You can dispatch Magento 2 Events using the Magento\Framework\Event\Manager class. This class can be obtained through dependency injection by defining the dependency in the constructor method of the 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, performance, 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.

Using Events and Observers in Magento 2

Magento 2 can execute the multiple numbers of observers for a single event trigger.

In this introductory article, I will discuss the use of Magento 2 events and observers. In addition, I will demonstrate the modification of the Product Name only on the product view page using Magento 2 events and observers.

Let’s start by creating a simple module with the namespace Magebay and the module name EventsObservers.

Create registration.php in app/code/Magebay/EventsObservers directory and add the following code to it:

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Magebay_EventsObservers',
    __DIR__
);

Now, create a module.xml file in the Magebay/EventsObservers/etc directory and add the following code to it:

<?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="Magebay_EventsObservers" setup_version="1.0.0"/>
</config>

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

Admin area: Namespace/ModuleName/etc/adminhtml/events.xml

Frontend area: Namespace/ModuleName/etc/frontend/events.xml

Global area: Namespace/ModuleName/etc/events.xml

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 Magebay/EventsObservers/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="MagebayProductData" instance="Magebay\EventsObservers\Observer\Product\Data" />
    </event>
</config>

The above XML code is listening for the catalog_controller_product_view event. Note that the name and instance attributes are in the <observer> element. Thename 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.

Now, create an Observer file Data.php in Magebay/EventsObservers/Observer/Product directory and add the following code to it:

<?php
namespace Magebay\EventsObservers\Observer\Product;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class Data implements ObserverInterface
{
    /**
     * Below is the method that will fire whenever the event runs!
     *
     * @param Observer $observer
     */
    public function execute(Observer $observer)
    {
        $product = $observer->getProduct();
        $originalName = $product->getName();
        $modifiedName = $originalName . ' - Modified by Magento 2 Events and Observers';
        $product->setName($modifiedName);
    }
}

So, what’s going on in the above file? Let’s find out:

  • namespace Magebay\EventsObservers\Observer\Product is the namespace, which maps through the folder structure of our Magento 2 module.
  • use Magento\Framework\Event\Observer and use Magento\Framework\Event\ObserverInterface are the classes I am using in the observer class.
  • class Data implements ObserverInterface is the class, which is same as the file name. It implements the ObserverInterface class defined above.
  • public function execute(Observer $observer) is the execute() method. It takes the Observer class as an argument. Further, in the code, I get the product object through the magic method: getProduct().  Then, I get the product name, modify it and finally set the product name using setName() method on the product class.

Now once you’re done, run the following CLI command to apply the changes:

rm -rf var/di/* var/generation/* var/cache/* var/log/* var/page_cache/*
php bin/magento cache:clean
php bin/magento cache:flush
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento indexer:reindex

Hope it helps. If you have an any ideal about our modules : Magento 2 Multi Vendor Marketplace Extension,Booking System Pro, Online product designer, you can comment under this post. I hope you will build great Magento 2 Extension for your website and Project