This Article is about how to create a custom event and observer in Magento 2, Magento 2 provides a wide list of Events through which you can implement the core functionality of Magento. It uses Event driven Model that is based on the Publish-Subscribe pattern. Using events and observers, You can execute your custom code in your observer by using Magento default event or custom Event. When an Event is dispatched, it is the responsibilty of observer to execute your custom code.
A General Definition of an Event
The Simplest meaning of an Event is an Action. It may be like –
1. Pressing a key from your keyboard,
2. clicking or double-clicking your mouse,
3. clicking any button on your page etc.
In Magento 2, An Event is an action that someone triggers at any specific amount of time. Although, There is a wide list of predefined Events in Magento and you can also create your own custom events.
Where to place your Event
All events can be place in events.xml file but this file can be created at some specifc areas. these are –
1. global: place events.xml file under etc/events.xml
2. adminhtml : place events.xml file under etc/adminhtml/events.xml
3. crontab : place events.xml file under etc/crontab/events.xml<
4. frontend : place events.xml file under etc/graphql/events.xml
5. graphql : place events.xml file under etc/webapi_rest/events.xml
6. webapi_rest : place events.xml file under etc/webapi_rest/events.xml
7. webapi_soap : place events.xml file under etc/webapi_soap/events.xml
Dispatching an Event
In Magento dispatching an Event is done by the dispatch() function of Magento\Framework\Event\ManagerInterface class. in this function you must pass the name of the event and array data as second parameter. like –
public function dispatch($customEventName, array $data = []);
where,
$customEventName : The name of your custom Event.
$data : data which you want to fetch in your observer class.
Observers
Observers are classes that can change the behavior and the business logic of an Event.
when an event gets fired, the observer reacts to the related event and executes your custom code which you have mentioned in your observer. Observers get executed whenever an Event is dispatched by the event manager.
Your observer should be placed under the Observer directory of your folder and must use Magento\Framework\Event\Observer and Magento\Framework\Event\ObserverInterface classes.
In Magento 2, to dispatch an event, you have to call the dispatch() function of the event manager class and provide the name of the Event and the array of data that you want to serve your observer class.
Here is a sample code to create a custom Event in Magento 2
Step 01: Dispatch an Event
To dispatch an Event you have to create a Controller and call the dispatch function of EventManager class. Path is Bluethinkinc/CustomEvent/Controller/Index/Index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php /** * Copyright © BluethinkInc All rights reserved. * See COPYING.txt for license details. */ namespace Bluethinkinc\CustomEvent\Controller\Index; use Magento\Framework\App\Action\Action; use Magento\Framework\DataObject; class Index extends Action { public function execute() { $customData = new DataObject([ 'name' => 'bluethinkinc', 'email' => 'bluethinkinc@gmail.com', 'description' => 'This is a sample text' ]); $this->_eventManager->dispatch('my_custom_event', [ 'result' => $customData ]); } } |
Step:02 Create events.xml file
Where you specify the name of your custom event and the name of your observer class. Path is Bluethinkinc/CustomEvent/etc/events.xml
1 2 3 4 5 6 7 8 9 10 11 12 |
<?xml version="1.0"?> <!-- /** * Copyright © BluethinkInc All rights reserved. * See COPYING.txt for license details. */ --> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> <event name="my_custom_event"> <observer instance="Bluethinkinc\CustomEvent\Observer\CustomObserver" name="my_custom_observer"/> </event> </config> |
Step:03 Create observer class
The observer keeps watch on your event and reacts when the event gets triggered. Path is Bluethinkinc/CustomEvent/Observer/CustomObserver.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php /** * Copyright © BluethinkInc. All rights reserved. * See COPYING.txt for license details. */ namespace Bluethinkinc\CustomEvent\Observer; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; class CustomObserver implements ObserverInterface { /** * the method gets executed when an event will fire. * * @param Observer $observer */ public function execute(Observer $observer) { $data = $observer->getEvent()->getResult(); print_r($data); // you will get your custom Data name,email and description } } |
Run commands and get your custom data
php bin/magento setup:di:compile
php bin/magento cache:flush
Tips to make your observer efficient
1. Always try to make your observer fewer lines of code. you should avoid lengthy and complex code in your observer, beacuse it can slow down your application.
2. It is a good practice to encapsulate your business logic in any other class that your observer uses.
3. If you do not want to run your observer you can disable it by setting the disabled value to true, because by default this value is false.
bluethinkinc_blog
2023-02-23