Magento2 Event Observer

In this blog post, we will see how to create a simple event observer in Magento2.

Steps to create our custom event observer in Magento2:
1) We need to create a Namespace_ModuleName or VendorName_ModuleName like Magetec_Predispatch.
Location: app/code/Magetec/Predispatch

2) Next we need to create a registration xml file of our module
Location: app/code/Magetec/Predispatch/etc/module.xml


<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">

3) Now we need to register our module in magento framework directory
Location: app/code/Magetec/Predispatch/Registration.php


<?php
MagentoFrameworkComponentComponentRegistrar::register(
MagentoFrameworkComponentComponentRegistrar::MODULE,
'Magetec_Predispatch',
__DIR__
);

4) Next we need to enable our module in magento environment by two alternative ways
a) Go to “app/etc/config.php” and edit file to add ‘Magetec_Predispatch’ => 1
OR
a) Go to command shell and run command “php bin/magento module:enable Magetec_Predispatch” (this will enable our module)
b) Go to command shell and run command “php bin/magento setup:upgrade” (this will register / upgrade our module version in database)

5) Now we will declare our custom observer in XML
Location: app/code/Magetec/Predispatch/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="controller_action_predispatch">
        <observer name="magetec_controller_action_predispatch" instance="Magetec\Predispatch\Observer\Predispatch" />
    </event>
</config>

6) Create our event observer class file

Location: app/code/Magetec/Predispatch/Observer/Predispatch.php


<?php
namespace Magetec\Predispatch\Observer;

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

class Predispatch implements ObserverInterface
{

protected $logger;

public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}

public function execute(Observer $observer)
{
$this->logger->warn('Observer message is logged');
//exit; uncomment this line to check its working
}
}

That’s it! you have created your custom frontend event observer.

Advertisements