Magento 2: Event Observer

This article shows how you can create event observer in a custom module in Magento 2.

In Magento 2, there is a separate xml file where you can define your event observer. For frontend events, you need to write your code in app/code/YourCompany/YourModule/etc/frontend/events.xml and for admin events, you need to write event observer code in app/code/YourCompany/YourModule/etc/adminhtml/events.xml.

Remember that, you need to place your Observer class in app/code/YourCompany/YourModule/Observer/ directory.

In the following example, we will be observing the event checkout_onepage_controller_success_action. This event is dispatched when the order is placed and we go to the checkout success page. You can get the list of all the events dispatched in Magento 2 from here: List of all dispatched events in Magento 2.

Here, I suppose that your module is named YourCompany_YourModule.

Let’s first create the events.xml file. This is our frontend events as the event is dispatched on checkout success page in frontend.

app/code/YourCompany/YourModule/etc/frontend/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='checkout_onepage_controller_success_action'>
        <observer
                name='YourCompany_YourModule_HelloWorld'
                instance='YourCompany\YourModule\Observer\HelloWorld'
                disabled = false
        />
    </event>
</config>

Here,

name = unique observer name
instance = full class name of the observer
disabled = enable/disable observer (default value is false)

In the above events.xml code, we have defined Observer class as HelloWorld. Below is the Observer class code. Our code should be in execute function of the HelloWorld class.

app/code/YourCompany/YourModule/Observer/HelloWorld


<?php

namespace YourCompany\YourModule\Observer;

use Magento\Framework\ObjectManager\ObjectManager;

class HelloWorld implements \Magento\Framework\Event\ObserverInterface {

    /** @var \Magento\Framework\Logger\Monolog */
    protected $_logger;
    
    /**
     * @var \Magento\Framework\ObjectManager\ObjectManager
     */
    protected $_objectManager;
    
    protected $_orderFactory;    
    protected $_checkoutSession;
    
    public function __construct(        
        \Psr\Log\LoggerInterface $loggerInterface,
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Sales\Model\OrderFactory $orderFactory,
        \Magento\Framework\ObjectManager\ObjectManager $objectManager
    ) {
        $this->_logger = $loggerInterface;
        $this->_objectManager = $objectManager;        
        $this->_orderFactory = $orderFactory;
        $this->_checkoutSession = $checkoutSession;        
    }

    /**
     * This is the method that fires when the event runs.
     *
     * @param \Magento\Framework\Event\Observer $observer
     */
    public function execute(\Magento\Framework\Event\Observer $observer ) {     
        
        $orderIds = $observer->getEvent()->getOrderIds();
        
        if (count($orderIds)) {
            $orderId = $orderIds[0];            
            $order = $this->_orderFactory->create()->load($orderId);
            $shippingAddress = $order->getShippingAddress();
            
            // do something
            // your code goes here
            
            $this->logger->debug('Logging HelloWorld Observer');            
        }
    }
}

Read more about Magento 2 Events and Observers in the Official Magento doc: Magento 2 Events and Observers.

Hope this helps.
Thanks.