X
    Categories: Magento 2 BlogsMagento Tutorials, Tips and Guides

An Introduction To Magento 2 Events and Observers

Working with events and observers is one of the ways to extend the core functionalities of the Magento Platform. Magento 2 provides the same events and observers customization options as Magento 1. The implementation of the events and observers in Magento 2 is based on the Publish-Subscribe pattern. Using Magento 2 events and observers, you can create and run custom code in response to a specific native or custom Magento event.

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 Cloudways and the module name EventsObservers. Create registration.php in Magento2Root/app/code/Cloudways/EventsObservers directory and add the following code to it:

<?php

\Magento\Framework\Component\ComponentRegistrar::register(

    \Magento\Framework\Component\ComponentRegistrar::MODULE,

    'Cloudways_EventsObservers',

    __DIR__

);

Now, create a module.xml file in the Cloudways/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="Cloudways_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 Cloudways/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="CloudwaysProductData" instance="Cloudways\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. 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.

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

<?php

 

namespace Cloudways\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 Cloudways\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

Before implementing the code, the product view looks like:

Once the Observer is triggered, the result will be something like this:

As the observer is listening for the catalog_controller_product_view event, it will only make changes to the product view. Thus, the category view will remain unchanged (default):

Fayyaz Khattak :Fayyaz is a Magento Community Manager at Cloudways - A Managed Magento Hosting Platform. His objective is to learn & share about PHP & Magento Development in Community. Fayyaz is a food lover and enjoys driving. You can email him at m.fayyaz@cloudways.com