Back to Top

Observers in Magento 2

Updated 22 February 2024

Today we are discussing observer in Magento 2.

To create observer in Magento 2, first we need to define observer in file:

app/code/Webkul/Hello/etc/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="controller_action_catalog_product_save_entity_after">
        <observer name="Webkul_Hello_Product_Save_After" instance="Webkul\Hello\Observer\productSaveAfter" />
    </event>
</config>

Note: There are different places to create files for different handlers.

  1. To create observer for frontend you can create file under : app/code/Webkul/Hello/etc/frontend/events.xml
  2. To create observer for frontend you can create file under : app/code/Webkul/Hello/etc/adminhtml/events.xml
  3. To create observer for both end, you need to create file under : app/code/Webkul/Hello/etc/events.xml

After this file, you need to create your observer file at the path you have mentioned above, i.e.:

Searching for an experienced
Magento 2 Company ?
Find out More

app/code/Webkul/Hello/Observer/productSaveAfter.php

<?php
namespace Webkul\Hello\Observer;

use Magento\Framework\Event\ObserverInterface;

class productSaveAfter implements ObserverInterface
{
    /**
     * @var ObjectManagerInterface
     */
    protected $_objectManager;

    /**
     * @param \Magento\Framework\ObjectManagerInterface $objectManager
     */
    public function __construct(
        \Magento\Framework\ObjectManagerInterface $objectManager
    ) {
        $this->_objectManager = $objectManager;
    }

    /**
     * customer register event handler
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return void
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        //Do your stuff here!
        die('Observer Is called!');
    }
}

Thank you for reading this article on Observers in Magento 2, we hope you liked it.

You can also view our wide range of ready-to-use Magento 2 extensions.

Further for any more queries, please reach out to our team via support ticket.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


5 comments

  • Anonymous
    • ashutosh srivastava (Moderator)
  • Qa Test0110
  • Ali Saleem
    • Akbar Adeeb
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home