In this tutorial, I will guide you through the popular events and observers which works based on event driven architecture which is also referred as publish-subscribe pattern.
We have already learned plugins in Magento 2, which allows you to modify or extend the behaviour of public methods in Magento 2 classes without overriding them. Let’s see how you can do this with the help of events and observers in Magento 2.
Magento 2 Observers are like those dedicated friends who always show up when called—except here, they respond to events in your application. Observers allow developers to extend functionalities without altering core files, making them essential for customizing Magento 2 without breaking your store.
Events
Events are predefined “triggers” in Magento 2 that occur when specific actions take place, such as saving a product, placing an order, or logging in as a customer.
Let’s see below example,
$this->_eventManager->dispatch(
'checkout_cart_update_items_after',
['cart' => $this, 'info' => $infoDataObject]
);
Magento uses the observer pattern through the \Magento\Framework\Event\ManagerInterface
and its implementation in the form of the \Magento\Framework\Event\Manager
class, which is responsible for managing events and dispatching them.
$this->_eventManager->dispatch(...)
: This calls thedispatch
method on the event manager object, which is responsible for triggering events in Magento 2.'checkout_cart_update_items_after'
: This is the name of the event being dispatched. Other parts of the system can listen for this event and execute custom logic when it is triggered.['cart' => $this, 'info' => $infoDataObject]
: This is an array of data being passed along with the event. It includes:'cart' => $this
: The current cart object.'info' => $infoDataObject
: An object containing additional information related to the cart update.
This event is typically used to allow other parts of the system to perform actions after the cart items have been updated.
Observers
Observers are like listeners. They “observe” events and execute custom code when a specific event is triggered.
Depending on the area from which we want to observe events, We can define observers in one of the following XML files :
app/code/{vendorName}/{moduleName}/etc/events.xml
app/code/{vendorName}/{moduleName}/etc/frontend/events.xml
app/code/{vendorName}/{moduleName}/etc/adminhtml/events.xml
Let’s understand it via below example,
Creating the Observer
Create Observer Class
<?php
namespace Jigar\CustomModule\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;
class CheckoutCartUpdateAfter implements ObserverInterface
{
protected $logger;
public function __construct(
\Psr\Log\LoggerInterface $logger
) {
$this->logger = $logger;
}
public function execute(Observer $observer)
{
$cart = $observer->getEvent()->getCart();
$info = $observer->getEvent()->getInfo();
// Access cart items
$items = $cart->getItems();
// Access the update info
$updateInfo = $info->getData();
// Your custom logic here
// For example, log cart updates
$this->logger->info('Cart updated with items: ' . json_encode($updateInfo));
// You can also:
// - Update related entities
// - Send notifications
// - Modify cart items
// - Trigger additional processes
// Log cart updates
$this->logger->info('Cart updated with items: ' . json_encode($info->getData()));
return $this;
}
}
Register the observer
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="checkout_cart_update_items_after">
<observer name="jigar_custom_checkout_cart_update" instance="Jigar\CustomModule\Observer\CheckoutCartUpdateAfter" />
</event>
</config>
Event observers provide a clean way to extend Magento 2 functionality. By following these patterns, you can add custom business logic while maintaining code modularity and avoiding core modifications.
You may also like
Mastering Plugins in Magento 2: A Beginner-to-Expert Guide
How to Use ViewModel in Magento 2: A Simple Guide
Magento 2: How to Check Cron Job is Working?
Frequently Asked Questions (FAQs)
Yes, you can create custom events using the dispatchEvent
method provided by Magento’s event manager.
Use Magento’s logging system (Psr\Log\LoggerInterface
) or tools like Xdebug. Ensure the events.xml
syntax is correct.
Observers react to events, while plugins intercept and modify method behavior. Choose based on your use case.
Explore the events.xml
files under the vendor/magento
directory or enable debug logging to capture triggered events.
Yes, you can. Just add multiple <event>
entries in the events.xml
file pointing to the same observer class.
Leave a Comment