Event and Observer in Magento 2

 we have to declare event that we will catch in file di.xml and a function on Observer file.

Example: echo module name, controller name, action name of the current module.

Event used:  controller_action_predispatch

1. Declare Event in events.xml (frontend)

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/Event/etc/events.xsd">
<event name="controller_action_predispatch">
<observer name="magenhub_event" instance="Magenhub\Chris\Model\Observer" method="printInfo" shared="false" />
</event>
</config>

This code will be write in module: Magenhub_Chris, model Observer.

2. Write file Observer.php

Write function printInfo to print module name, controller name, action name of the current url.

File: app/code/Magenhub/Chris/Model/Observer.php

<?php

namespace Magenhub\Chris\Model;

class Observer {

public function printInfo(\Magento\Framework\Event\Observer $observer) {
$request = $observer->getEvent()->getData('request');
echo $request->getModuleName('catalog').'<br/>';
echo $request->getControllerName('product').'<br/>';
echo $request->getActionName('view').'<br/>';
die();
}

}
 

This code only print module name, controller name and action name to browser.

  • Result for home page:

cms
index
index

  • Result for product view page:

catalog
product
view