• ecommerce
  • Magento
  • Technical

How to Dispatch Custom Events in Magento 2

In this blog, we'll explore how to dispatch custom events in Magento, expanding on the concepts of events and observers discussed in last article

How to Dispatch Custom Events in Magento 2

In this blog, we’ll explore how to dispatch custom events in Magento, expanding on the concepts of events and observers that we discussed in our previous tutorial. If you’re familiar with observing predefined Magento events, you’ll find it quite straightforward to dispatch your own custom events. Let’s dive in.

Full Video Walkthrough by CodeWithAli

Recap: Observing Predefined Magento Events

In our last tutorial, we covered how to observe predefined Magento events using the Observer class. Observers allow us to react to specific events that occur within Magento, like customer login, order placement, etc. Now, we’ll take it a step further by learning how to fire a custom event from our own code.

read previous blogs of the series

Introduction of Events and Observers

Dispatching a Custom Event

Magento provides a simple way to dispatch custom events through the Manager Interface “Magento\Framework\Event\ManagerInterface”. This interface allows us to trigger events programmatically, which can then be observed by our custom observers.

Step 1: Set Up the Event Manager Interface

First, we’ll need to inject the “EventManager” interface into our class using dependency injection. This will enable us to dispatch events from within our methods.

Go to the LoginAfter Observer we created in the last tutorial “Observer/LoginAfter.php” and make the following changes

PHP
<?php

namespace Demo\EventObservers\Observer;

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

//add the following line to call the Event Manager Interface
use Magento\Framework\Event\ManagerInterface;


class LoginAfter implements ObserverInterface
{
    //dependency injection: "public ManagerInterface $manager" 
    public function __construct(public LoggerInterface $logger, public ManagerInterface $manager) {
    }

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

Step 2: Dispatch the Event

To dispatch an event, we use the dispatch method of the EventManager class. This method requires at least one parameter: the event name. You can also pass additional data as an associative array.

Note: The additional information has to be in an array

Let’s apply this to our example. We’ll dispatch an event named observer_login_after when a customer logs in. Here’s how the code will look like:

PHP
<?php

namespace Demo\EventObservers\Observer;

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

//add the following line to call the Event Manager Interface
use Magento\Framework\Event\ManagerInterface;


class LoginAfter implements ObserverInterface
{
    //dependency injection: "public ManagerInterface $manager" 
    public function __construct(public LoggerInterface $logger, public ManagerInterface $manager) {
    }

    public function execute(Observer $observer)
    {
        $data = $observer->getData();
        $this->logger->debug(print_r($data, true));
        
        //dispatch Event using the dispatch method
         $this->manager->dispatch(
            'eventobservers_login_after',
            [
                'customerEmail' => $observer->getData('customer')['email'],
                'customerId' => $observer->getData('customer')['id']
            ]
        );
    }
}

Creating an Observer for Our Event

Now that we’ve dispatched the event, the next step is to observe it.

Step 1: Configure the Event in events.xml

To observe the custom event, you need to configure it in the events.xml file “etc\frontend\events.xml” of your module. This tells Magento which observer to trigger when the event occurs.

XML
    <event name="eventobservers_login_after">
      <observer name="eventobsevers_login" instance="Demo\EventObservers\Observer\EventObserversLoginAfter"/>
    </event>

In the above code, custom_observer_login_after is the unique name of our observer, and Demo\EventObservers\Observer\EventObserversLoginAfter is the class that will handle the event.

Step 2: Create the Observer Class

Next, we’ll create the observer class that will handle our custom event inside the Observer folder and name it EventObserversLoginAfter.php

PHP
<?php

namespace Demo\EventObservers\Observer;

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

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

    public function execute(Observer $observer)
    {
        // the data is the data fetched from the custom event we created
        $data = $observer->getData();
        $this->logger->debug('++++++++ Custom Event ++++++++++');
        $this->logger->debug(print_r($data, true));
    }
}

Testing the Observer

Finally, to see everything in action, clear the cache, log out, and then log in again. Check your logs, and you should see an entry for the custom event with the customer’s email and ID.

In this tutorial, we’ve successfully covered how to dispatch a custom event in Magento and how to observe it with a custom observer. Understanding these concepts will give you more control over your Magento application, allowing you to create more dynamic and responsive features.

Stay tuned for more tutorials on Magento development!

Would you like to share this article?

Share

need assisting with Magento 2 customization?

Feel Free To Contact Our Experts