Site icon MageComp Blog

How to Create Events Observer in Magento 2

How to Create Events Observer in Magento 2

How to Create Events Observer in Magento 2

The events in Magento 2 architecture helps extending the default functionality of it. It is a flag that rises at the occurrence of some specific situation for example, click “submit” button on contact page is an event performed by website visitors. An observer works as a listener that detects events and performs an action defined at the time of event occurrence.

It allows adding own logic to the core code without changing core files or code. Having powerful event/observer pattern, we can use it very effectively in Magento 2 custom modules.

Catching and handling an Event:

Area definition is used by Magento to manage the store. We will have frontend area and admin area where we can put area definition with configuration file:

Create events configuration file for each area like this:

Implementation of event/observers in Magento 2 is based on public-subscribe pattern. Magento 2 can execute any number of observers for an event occurrence. Here, we will learn to create events observers in Magento 2.

Detailed Guide on Creating Event Observer in Magento 2:

In Magento 2, Magento\Framework\Event\ManagerInterface interface is responsible for dispatching the events.
Magento/Checkout/Model/Cart.php

namespace Magento\Checkout\Model;

use Magento\Checkout\Model\Cart\CartInterface;
use Magento\Framework\DataObject;
 
class Cart extends DataObject implements CartInterface
{
    ...
   public function save()
   {
       $this->_eventManager->dispatch('checkout_cart_save_before', ['cart' => $this]);
       //Perform save cart action
       $this->_eventManager->dispatch('checkout_cart_save_after', ['cart' => $this]);
       return $this;
   }
   ...
}

Here, we are dispatching ‘checkout_cart_save_before’ and ‘checkout_cart_save_after’ events and thus we can now easily trigger any action before and after the cart is saved. This helps avoiding rewrite of the entire class.
Magento allows passing values to the observers to trigger the action on event occurrence as you saw in above example.

Custom Events:
To dispatch custom events in Magento 2, create an object for Magento\Framework\Event\ManagerInterface and pass the unique custom event name to the object.

$this->_eventManager->dispatch(‘custom_action_after_save’, [‘param’ => $this]);

Here, parameters are optional.

Mapping Events and Observer:
To configure the observers to certain events, Events.xml files is responsible.

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="magecomp_mymodule_event_after">
        <observer name="magecomp_mymodule_event_after_observer" instance="Magecomp\MyModule\Observer\MyObserver"/>
    </event>
</config>

observer node is having following properties:

Observers:
Observers are executed when the mapped event is triggered. Event Manager is responsible for dispatching events and executing the respective observers.

namespace MAGECOMP\MyModule\Observer;
 
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
 
class MyObserver implements ObserverInterface
{
 
 public function execute(Observer $observer)
 {
    // get parameters passed in events
    $cart = $observer->getData('param');
 
    //Perform action
 }
 
}

The above structure is a basic observer class. Note that Observer class must implement \Magento\Framework\Event\ObserverInterface.

I hope this blog has helped you to create and implement events observer in Magento 2.

If you stuck with something while implementation, let me know through commenting. I’ll be happy to assist you.

Exit mobile version