How to handle events

observer
event
area
(Dmitry Fedyuk) #1

Step 1

Declare event handlers in a module’s events.xml file.
A module can have multiple events.xml files:

A module's `events.xml` files
Location Where do the handlers are triggered Example
`etc/events.xml` Everythere. [`Magento/CatalogInventory`][1]
`etc/adminhtml/events.xml` In admin interface only. [`Magento/Catalog`][2]
`etc/frontend/events.xml` In frontend interface only. [`Magento/Catalog`][3]
`etc/crontab/events.xml` While handling scheduled ([cron][4]) jobs only. [`Magento/CatalogRule`][5]
`etc/setup/events.xml` While Magento or extensions are being [installed][6] or [upgraded][7]. [`Magento/CatalogUrlRewrite`][8]
`etc/webapi_rest/events.xml` While handling [REST][9] [API][10] requests. [`Magento/CatalogRule`][11]
`etc/webapi_soap/events.xml` While handling [SOAP][12] [API][13] requests. [`Magento/CatalogRule`][14]

An example of event handler declaration in events.xml:

<?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>

Step 2

Create the event handler class.
The class shoud implement \Magento\Framework\Event\ObserverInterface.
The interface has the single method execute and it shoud be implemented:

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

Please note that event handler declaration has been significanlty changed in October 2015:


0 Likes

Whats the difference if I place events.xml directly under etc folder, under etc/frontend or etc/adminhtml?
How can an extension do a custom initialization on Magento start?