Jigar KarangiyaJigar Karangiya

How to Get a list of all observers of specific events in Magento 2

JK
Jigar Karangiya
· 1 min read
How to Get a list of all observers of specific events in Magento 2

Hello Devs, In this tutorial we will see how to get a list of all observers of specific events in Magento 2 programmatically.

Suppose you are debugging some code and you get a requirement to find all observers which are triggered when a specific event occurs.

Suppose that, you want to find the list of observers of the “sales_order_place_after” event.

In this situation, you can simply get all the observer lists using the below snippet code.

In Magento 2, You can get observers by event name using “Magento\Framework\Event\Config ” class.

We can use getObservers() method to fetch an array of all the observers by passing the event name.

Here is the example code you can use :

php
<?php
class YourClass {
    public function __construct(
    \Magento\Framework\Event\Config $eventConfig
    ) {
        $this->eventConfig = $eventConfig;
    }
 
    public function getObservers(string $eventName = null)
    {
        /* here you will get array of all observers containing observer name,instance with name as key for each observer for the specified event */
        $observersData = $this->eventConfig->getObservers($eventName);
        /*as we want only observer names here, we can use below code*/
        $observers = [];
        foreach ($observersData as $observerName => $config) {
            $observers[] = $observerName;
        }
        return $observers;
    }
}

Then you can call this function by passing the event name in an argument like below.

php
$this->getObservers('sales_order_place_after');

If you print the data, It will return the array list of all observers in the below format.

json
[
    "sales_vat_request_params_order_comment",
    "magento_giftregistry",
    "login_as_customer_log_place_order",
    "newrelicreporting_observer_report_sales_order_place",
    "newrelicreporting_newrelic_report_sales_order_place",
    "ddg_sales_order_place_after",
    "stripe_payments_place_order_after",
  ]

You will also love reading this :

Store Emulation in Magento 2.

That’s it for this tutorial. Thank you for reading. Happy coding !!

Written by Jigar Karangiya, Adobe Commerce & Magento 2 developer.

More about me

Related posts