This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Join our live AMA on the Future of Page Builders with Brizy's CEO! Register Now →

An Introduction To Magento 2 Events and Observers

Updated on December 24, 2021

4 Min Read
magento 2 observer

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.

Managed Magento Hosting for an Instant Performance Boost

Launch your Magento store in minutes and witness a CRAZY speed & performance boost.

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

Optimize Magento Speed Like a Pro

Subscribe now and get a free ebook to your inbox.

Thank You

Your Ebook is on it’s Way to Your Inbox.

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:

Product View

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

Magento Observer Trigger

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):

Magento Observer View

Share your opinion in the comment section. COMMENT NOW

Share This Article

Abdur Rahman

Abdur Rahman is the Magento whizz at Cloudways. He is growth ambitious, and aims to learn & share information about Ecommerce & Magento Development through practice and experimentation. He loves to travel and explore new ideas whenever he finds time. Get in touch with him at [email protected]

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now