Introducing Event Observer in Magento 2 and its Benefits

Posted by

In the intricate landscape of Magento 2 development, the Event Observer design pattern emerges as a powerful tool for extending and customizing the platform’s functionalities. This article delves into the essence of the Event Observer pattern, its mechanics, benefits, and how it empowers developers to tailor Magento 2 to their unique needs. Event observers are essential for extending and customizing the behaviour of Magento without modifying its core code, promoting flexibility and maintainability in the development process.

Understanding Event Observer

At its core, the Event Observer pattern is a way to respond to specific events or triggers that occur during Magento 2’s execution. These events can range from order placements and product updates to customer registration and cart manipulations. By observing these events, developers gain the capability to execute custom code without modifying the core files.

There are 3 important things while creating Event Observer of Magento 2. They are Events configuration, Base and custom events and Observer.

Events configuration (events.xml)

In Magento 2, the “events.xml” file plays a crucial role in the event-driven architecture of the platform. This XML configuration file allows developers to define and declare event observers, specifying which events in the system trigger custom actions or code execution. In “events.xml,” developers specify the event name, the observer class responsible for handling the event, and the method within that class to execute when the event occurs. This structured approach to event handling is integral to Magento’s modular and extensible design, enabling seamless integration of custom functionalities into the e-commerce platform.

The file can be placed under etc or etc/admin. If the file is under etc then it will be applied to both frontend as well as admin. For example if you want to trigger specific event which will occur on both frontend and backend (admin) like order generation. If the events.xml file is placed under etc/admin then it will effect only at admin events. Like when you want to save a products and tigger an event.

Example of 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="sales_order_item_save_after">
<observer name="learning_magento_send_admin_notification" instance="Learningmagento\OrderNotification\Observer\SendNotificationObserver" />
</event>
</config>

Base and custom events

Base events are predefined events provided by the Magento framework, such as cart update or order placement. These base events are integral to Magento’s core functionality and serve as triggers for various built-in processes. Check the adobe link for a complete list on Magento core events.

$this->_eventManager->dispatch('adminhtml_sales_order_create_process_item_after', $eventData);

The above event is triggered from a Magento\Sales\Controller\Adminhtml\Order\Create inside of _processActionData() function.

Custom events, on the other hand, are events created by developers to respond to specific needs or to extend the functionality of the Magento platform. By defining custom events and event listeners (observers), developers can inject their code into Magento’s event execution flow, enabling them to customize and enhance the platform’s behaviour without modifying its core code.

In order to create a custom event you need to include an interface in your class where the event need to be triggered. You need to inject the Magento\Framework\Event\ManagerInterface interface in the class constructor. Then it can be dispatched along with data which the observer class can use it.

<?php
namespace Learningmagento\Hahoo\Controller\Cleaner;

use Magento\Framework\App\ActionInterface;

class Index extends ActionInterface
{
    protected $_eventManager;

    public function __construct(
      \Magento\Framework\Event\ManagerInterface $eventManager
    ) 
    {
      $this->_eventManager = $eventManager;
    }
    public function execute()
    {
        // Some code which will run.
        $this->_eventManager->dispatch('clearning_logs_after',
            [
                'cleanedFiles' => $somedata
            ]
        );
    }
}

Observer class

In Magento 2, the Observer class plays a vital role in the event-driven architecture of the platform. An Observer is a PHP class that listens for specific events dispatched within the Magento application. When an event is triggered, the associated Observer class’s method is executed, allowing developers to respond to and customize the default behavior of Magento without modifying its core code. This decoupling of custom functionalities from the core codebase enhances modularity and maintainability.

Observers are defined in XML configuration files which is events.xml , where developers specify the event they want to listen for. The example for this xml file is in the section of Events configuration (events.xml). An Observer class must implement the ObserverInterface and also should have implement method body for execute method. You code which need to do specific work need to go in this method.

<?php

namespace Learningmagento\Hahoo\Observer;

class StoreFilesNames implements \Magento\Framework\Event\ObserverInterface
{
public function execute(\Magento\Framework\Event\Observer $observer)
{
$files = $observer->getData('cleanedFiles');
foreach($files as $file) {
                   //Store file names code
                }
return $this;
}
}

Benefits of Event Observer Pattern

  1. Modularity: Event Observers foster modular development, allowing developers to create independent modules that enhance core functionalities without interfering with Magento’s core codebase.
  2. Flexibility: Customizations become more flexible as developers can attach multiple observers to a single event. This makes it easier to collaborate with third-party modules and adapt to various scenarios.
  3. Code Integrity: The pattern ensures code integrity by enabling developers to add functionality without modifying the original codebase. This reduces the risk of errors and conflicts during updates.
  4. Maintainability: With clean separation between core and custom code, future upgrades and maintenance are more streamlined, saving time and effort.

Overall of Event Observer in Magento 2

In the realm of Magento 2 development, the Event Observer design pattern stands as a cornerstone for customization and extension. Its ability to enhance modularity, flexibility, and code integrity elevates the developer’s toolbox. By mastering the intricacies of Event Observer, developers unlock a world of possibilities, allowing them to create tailored solutions that align with the specific needs of each Magento 2 project. There are other design patterns which are used in Magento. You can check them in the category of Design Pattern.