Quantcast
Channel: Webkul Blog
Viewing all articles
Browse latest Browse all 5554

Observers in Magento2

$
0
0

Today we are discussing observer in magento 2.

To create observer in magento2, 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/event.xml
  2. To create observer for frontend you can create file under : app/code/Webkul/Hello/etc/adminhtml/event.xml
  3. To create observer for both end, you need to create file under : app/code/Webkul/Hello/etc/event.xml

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

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!');
    }
}

Viewing all articles
Browse latest Browse all 5554

Trending Articles