How To Create Event Observer in Magento 2

Hello Everyone,

In this blog, we will learn about how to Create Event Observer in Magento 2.

The Event can extend the default functionality of Magento 2, without affecting to core code and core files.

We can use our custom logic when some event is performed.

Without wasting your time, let us guide you straight away. Follow the easy step given below to Create Event Observer in Magento 2.

STEPS FOR CREATE EVENT OBSERVER IN MAGENTO 2

Step 1: Create events.xml file

There are three area to declare events.xml file.

global area: app/code/Vendor/Extension/etc/events.xml
frontend area: app/code/Vendor/Extension/etc/frontend/events.xml
admin area: app/code/Vendor/Extension/etc/adminhtml/events.xml

app/code/Vendor/Extension/etc/frontend/events.xml

<?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_product_add_after">
         <observer name="magecurious_checkout_cart_product_add_after" instance="Vendor\Extension\Observer\CheckoutCartProductAddAfter" />
     </event>
</config>

Step 2: Create CheckoutCartProductAddAfter.php file

app/code/Vendor/Extension/Observer/СheckoutСartProductAddAfter.php

<?php

namespace Vendor\Extension\Observer;

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

class CheckoutCartProductAddAfter implements ObserverInterface
{
    protected $logger;

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

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $this->logger->info('Observer Called');
        $product = $observer->getProduct();
        $item = $observer->getQuoteItem();

        $product = $observer->getData('product');
        $item = $observer->getData('quote_item');
    }
}

Step 3: Finally run the below commands

$ php bin/magento cache:clean
$ php bin/magento cache:flush

Final Thoughts:

So this was the easiest way which we have told you in this blog. This is how you can Create Event Observer in Magento 2. Hope you liked the blog.

So quickly go to the comment box and tell me how you like this blog?

Stay tuned with us on our site to get new updates of Magento.

Thanks for reading and visiting our site.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Leave a Reply

Your email address will not be published. Required fields are marked *