Use magento2 observer

Magento2 observer

Use of magento2 observer in module development or extension creation was very important to implement the dynamic hooking system. To know more about the observer click here. In this article you will learn about the syntax rule of observers in magento2. The sample difference for syntax in magento2 observer from magento1 was described using the event ‘controller_action_predispatch’. This event trigger automatically by magento after the dispatch of every action in the controller.

Magento 1.x observer

To create observer in magento 1.x we need to initiate the observer events in config.xml file. Let us see the sample observer call “controller_action_predispatch”


Then in the oberver file Explorer\Test\Model\Observer.php create the method to execute it.

class Explorer_Test_Model_Observer{
	public function message(Varien_Event_Observer $observer) {
        Mage::log('observer dispatch executed', null, 'test.log');

Magento2 observer

In magento 2.0 the observer can be initated from the events.xml file in etc directory. You can segregate the events.xml for admin and frontend by creating two directories adminhtml and frontend in etc folder. For the event ‘controller_action_predispatch’ create the file name evnets.xml in the path Explorer/Test/etc/frontend/events.xml

  <?xml version='1.0'?>
<config xmlns:xsi='' xsi:noNamespaceSchemaLocation='../../../../../lib/internal/Magento/Framework/Event/etc/events.xsd'>
	<event name='controller_action_predispatch'>

The file ControllerActionPredispatch.php in ‘Explorer\Test\Model\Observer\’ folder.

namespace Explorer\Test\Model\Observer;
use Magento\Framework\Event\ObserverInterface;
class ControllerActionPredispatch implements ObserverInterface {
	public function __construct (
        \Psr\Log\LoggerInterface $logger
    ) {
        $this->_logger = $logger;
	public function execute(\Magento\Framework\Event\Observer $observer) {
		$this->_logger->addInfo('observer dispatch executed');

No Comments yet, your thoughts are most welcome