Magento2 – Events – Module Development Series – Part4

In this blog post we will see how events work in magento2

Events in magento is an important feature to extend core functionality. Let’s see how events work in magento2.

Event Basics

Events in magento follow the Observer Pattern which means, at many places in magento core modules events are emitted and we can write code in our custom module to listen to those events and perform actions.

Events are the always the best way to add features on top of core modules. Reason being they don’t conflict with other modules, multiple event observers can be attached to a single event.

How to setup events

To add events we first need to decide weather its a frontend event or admin event. Depending on this we need to create a configuration file

For frontend event

Excellence/Hello/etc/frontend/events.xml

For admin event

Excellence/Hello/etc/adminhtml/events.xml

for now we will look at frontend events only.

So in our module we add the file etc/frontend/events.xml , with the following content

<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="excellence_hello_test_observer" instance="Excellence\Hello\Observer\Predispatch" />
    </event>
</config>

The event name should be unique

Next let’s define the observer

Excellence\Hello\Observer\Predispatch.php

and write the code

<?php


namespace Excellence\Hello\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 Works');
        //exit; un commet this to make sure event works
    }
}

Since we have used the event ‘controller_action_predispatch’, this observer should work on every page. If you open any frontend page, you should see ‘Observer Works’ in var/log/system.log folder.

Let’s see another example of using events which is bit more complex.

To find event’s which are emitted through magento you need to open up core files and find events. Let’s write a code to log customer name when he gets logged in.
Looking at the model ‘Magento\Customer\Model\Customer’ we find the relevant event

$this->_eventManager->dispatch(
            'customer_customer_authenticated',
            ['model' => $this, 'password' => $password]
        );

Let’s write observer for this event in our events.xml file

<event name="customer_customer_authenticated">
        <observer name="excellence_hello_customer_customer_authenticated" instance="Excellence\Hello\Observer\Customer\Authenticated" />
    </event>

next let’s create the class

Excellence\Hello\Observer\Customer\Authenticated.php

with code

<?php


namespace Excellence\Hello\Observer\Customer;

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


class Authenticated implements ObserverInterface
{
   
    protected $logger;

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

    public function execute(Observer $observer)
    {
        $customer = $observer->getModel();
        //print_r($customer->getData());exit;
        $this->logger->warn('Customer Logged IN:' . $customer->getFirstname());
    }
}

In the above example we are able to see how to retrieve event data from $observer and use it