Magento 2 – Helloworld – Create Event and Observer

In this blogpost we will learn how to create event and observer in Magento2. Events observer is an important feature to extend core functionality of Magento without overriding. We can attach multiple observer to a single event and add our feature on top of magento core module.

How to setup events

To setup an event we mainly have three steps:-
1. Code from where an event will dispatch
2. Event xml file to know event name for which observer is created.
3. Observer file for our event(this will have the extended functionality)
There are three area for creating events configuration file i.e, events.xml file
1. Under etc/ folder: – This file has configuration which can be used in both admin and frontend area.
2. Under etc/frontend folder: – This file has configuration which can be used for frontend area.
3. Under etc/adminhtml folder: – This file has configuration which can be used for admin area.

Now we will be creating an event observer for ‘customer login’ and will log customer firstname on login of customer in magento application. Let start with the coding part:-
1. Create event.xml

 W3solver/Helloworld/etc/frontend/events.xml

So, in below code we have provided ‘customer_login’ as an event name, observer name is a unique identifier and instance contains class path to our observer file.


<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="customer_login">
        <observer name="w3solver_helloworld_customer_login" instance="W3solver\Helloworld\Observer\login" />
    </event>
</config>

2. Now we have to create observer file with the same path as provided in above class, observer class will extends Observer Interface and our code will be in execute function.

 W3solver\Helloworld\Observer\login.php

namespace W3solver\Helloworld\Observer;
 
use \Psr\Log\LoggerInterface;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
 
class Login implements ObserverInterface
{
    
    protected $logger;
   
    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }
 
    public function execute(Observer $observer)
    {
        $customer = $observer->getCustomer();
        $this->logger->warn('Customer Logged IN:' . $customer->getFirstname());
    }
}
 

Now you can check your system.log to get customer firstname.

Dispatch Event

To add your own custom event, you need to add below line of code at a place where you want event to dispatch:-

 $this->_eventManager->dispatch('helloworld_first_event', ['hello_content' => 'you have succesfully created first event']); 

Above code dispatch an event with name “helloworld_first_event” and attached a variable “hello_content”.

Leave a Comment.