• ecommerce
  • Magento
  • Technical

Introduction to Events and Observers in Magento 2

This article is about events and observer mechanism in Magento 2, it explores the default Magento events and how to write observers to listen to the events

How to Dispatch Custom Events in Magento 2

In the world of Magento development, understanding events and observers is crucial for creating flexible and extensible e-commerce solutions. This blog post will dive deep into the concept of events and observers in Magento, exploring their logical implementation, default Magento events, and how to create custom events.

It will be a 3-part tutorial where we will learn everything about events and observers in magneto 2.

In this part we will discuss:

Discussing the logical implementation of events and observers.

Understanding the default Magento events present in the core code and how to observe them.

Creating a custom event and dispatching it.

Full Video Walkthrough by CodeWithAli

Understanding Events and Observers

Events in Magento are specific actions or occurrences within the system. They can be likened to real-world events such as rain falling or a bird flying. Each event carries certain data related to the action that triggered it.

Observers, on the other hand, are classes configured to “listen” for specific events and perform actions based on those events. Think of observers as media organizations reporting on a news event – they record the event, gather information, and then act on it.

Event Areas in Magento

Magento provides different areas where events can be observed:

global: Observes events from frontend, backend, and APIs

adminhtml: For admin-specific events

crontab: For scheduled task events

frontend: For storefront events

graphql

webapi_rest

webapi_soap

Default Magento Events

Magento comes with a plethora of predefined events that are dispatched at various points in the system’s execution. Some examples include:

– controller_front_send_response_before
– cron_job_run
– customer_login
– customer_logout

These events provide developers with hooks to extend functionality without modifying core code.

You can find the full list of events from official Magento documentation

how to observe an event

Let’s walk through a practical example of observing the customer_login event

# Step 1 Create a Basic Module

We start by creating a basic module, named `Demo_EventObserver`, to observe the `customer_login` event.

# Step 2 Configure event

Under the `etc` directory, create an `events.xml` file to observe the `customer_login` event. Below is an example configuration:

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="customer_login">
        <observer name="customer_login_after" instance="Demo\EventObserver\Observer\LoginAfter" />
    </event>
</config>

# Step 3 Create the Observer Class

PHP
<?php

namespace Demo\Event\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;
use Psr\Log\LoggerInterface;

class LoginAfter implements ObserverInterface
{
    public function __construct(public LoggerInterface $logger)
    {
    }

    public function execute(Observer $observer)
    {
        $data = $observer->getData();
        $this->logger->debug(print_r($data, true));
    }
}

Testing the Observer

After implementing the observer, clear the Magento cache and test by logging in as a customer. The customer data should be logged in the debug.log file.

That’s it for this tutorial, now you might have some idea about how to leverage events and observers to create more flexible and maintainable Magento extensions. Remember to always consider performance implications when implementing observers, especially for frequently triggered events.

In this tutorial, we’ve covered the basics of events and observers, explored default Magento events, and implemented a practical example. In the next blog we will see how we can create the custom events.

Would you like to share this article?

Share

Would you like to integrate Whatsapp or APIs into your website or mobile app?

Feel Free To Contact Our Experts