Magento 2 Observers

This article sheds light on Magento 2 observers – event handlers that listen to events they are attached to and respond to these events. Since Magento 2 signifiantly differs from 1.X, the observers registration and creation include some new aspects described below.
- The first important change is the usage of an independent events.xml file, which is necessary for observer registration.
- The second difference introduced in Magento 2 is related to the way the system defines the scope of the observer. If previously the xml node has been used, now the system relies on the events.xml file location.
- The last vital aspect you should pay attention to is a revamped XML syntax.
Table of contents
Magento 2 Observers: Separate events.xml
As we’ve mentioned above, Magento 2 stores all module observers in an independent xml file under:
|
1 |
app/code/vendor/module/etc/events.xml(app/code/vendor/module/etc/adminhtml/events.xml |
Another place where you can find them is:
|
1 |
app/code/vendor/module/etc/frontpage/events.xml |
Let’s have a look at the example of an xml file:
|
1 2 3 4 5 6 7 |
<?xml version="1.0" encoding="UTF-8"?> ... <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/Event/etc/events.xsd"> <event name="controller_front_send_response_before"> <observer name="vendor_module_controller_front_send_response_before" instance="vendor/module\Model\Observer" method="verificate" /> </event> </config> |
You can see the event node and the name attribute that defines a special event which acts as a trigger that calls the observer.
As for the observer node, it defines not only the observer itself, but also its attributes, such as:
- name – the registration name of the observer. Not that it shouldn’t coincide;
- instance identifies a class and a method executed if a definite event takes place;
- method – the executed method.
Now, let’s see how the observer looks like (app/code/vendor/module/Model/Observer.php):
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php ... namespace vendor\module\Model; class Observer { protected $_moduleData; protected $_registry = null; public function __construct ( \vendor\module\Helper\Data $moduleData, \Magento\Framework\Registry $registry ) { $this->_moduleData = $moduleData; $this->_registry = $registry; } public function verificate(\Magento\Framework\Event\Observer $observer) { ... } ... } |
The only significant difference here is related to the way the classes are named. In the aforementioned example, the verificate function receives a current observer object as an argument.
Magento 2 Observers: The observer scope definition
Now, let’s shed light on the observer scope definition mentioned above. Just look at the following config.xml file:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<frontend> <events> <vendor_jquery_dispatch_before> <observers> <vendor_module_jquery_dispatch_before> <type>singleton</type> <class>module/observer</class> <method>verificate</method> </vendor_module_jquery_dispatch_before> </observers> </vendor_jquery_dispatch_before> </events> </frontend> |
In case of 1.x, this approach has been used to define the observer on the frontend only. However, Magento 2 defines the scope of the observer by the events.xml file and its location.
For frontend it is
|
1 |
app/code/Namespace/Modulename/etc/frontend/ |
For admin:
|
1 |
app/code/Namespace/Modulename/etc/adminhtml/ |
For both locations:
|
1 |
app/code/Namespace/Modulename/etc/ |
Magento 2 Observers: Other useful materials
If you are not familiar with events.xml configuration files, they contain event/observer configuration. Their stage is characterised with two terms: global and area. As for the Configuration object, it is . For further information, check this manual: .
In its turn, Magento\Framework\Event includes the code responsible for publishing synchronous events as well as handling observers for any Magento event. For further information, follow this link: .
The way you can get the list of events/observers in Magento 2 is described here: How to get Magento 2 events/observers.
If you want to handle events:
- Take a module’s events.xml file and declare event handlers there.
- Check the following example of event handler declaration:
|
1 2 3 4 5 6 7 8 9 |
<?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='Df\Core\Observer\ControllerActionPredispatch' instance='Df\Core\Observer\ControllerActionPredispatch' /> </event> </config> |
Now, you can create a new event handler class. Note that it should implement with a single method. The interface should be handled as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php namespace Df\Core\Observer; use Magento\Framework\Event\ObserverInterface; class ControllerActionPredispatch implements ObserverInterface { /** * @override * @see ObserverInterface::execute() * @used-by \Magento\Framework\Event\Invoker\InvokerDefault::_callObserverMethod() * @see \Magento\Framework\App\Action\Action::dispatch() * https://github.com/magento/magento2/blob/dd47569249206b217e0a9f9a9371e73fd7622724/lib/internal/Magento/Framework/App/Action/Action.php#L91-L92 $eventParameters = ['controller_action' => $this, 'request' => $request]; $this->_eventManager->dispatch('controller_action_predispatch', $eventParameters) * @param \Magento\Framework\Event\Observer $observer * @return void */ public function execute(\Magento\Framework\Event\Observer $observer) { rm_state()->controllerSet($observer['controller_action']); } } |
For further information, check this post: .
____
Have any questions regarding Magento 2 observers? Leave them in comments







