Hey Magento folks, this article is based on Magento2 1.0.0 beta version. I will be briefly explaining the event observers in Magento2. Developers who have worked on Magento 1.x series are well aware the importance of events-observers in terms of developing custom functionality, and a way to avoid core code modification.
In Magento2 , it is nearly the same concept, just the aesthetics of using it has changed. So lets dive into it without any further ado.
Contrary to Magento 1.x, all event defintions fo into a seperate xml file i.e events.xml
So in your module folder, there could be three events file.
So as you might have guessed first file is for global scope and then frontend , adminhtml respectively.
So late’s say, i need to observer event, checkout_cart_add_product_complete
i will create an events.xml
<?xml version=“1.0” encoding=“UTF-8”?>
<observer name=“techbuzz_custom_checkout_cart_add_product_complete” instance=“Techbuzz\Custom\Observer\CompleteObserver” />
ok, so here the in events tag, name is given as the event name. In the observer tag we have
1. name = name of the observer – which should be unique
2. instance = class name which will contain this observer
So, in my module i.e. Techbuzz\Custom\Observer
class CompleteObserver implements ObserverInterface
* @param \Magento\Framework\Event\Observer $observer
* @return void
public function execute(\Magento\Framework\Event\Observer $observer)
//execute your code here
Okie, so going deep into, how the events are initialize
//file \Magento\Checkout\Controller\Cart\Add.php -113
[‘product’ => $product, ‘request’ => $this->getRequest(), ‘response’ => $this->getResponse()]
Where event manager is a object of \Magento\Framework\Event\ManagerInterface
So in same way we could initialize and fire our own custom events.
You can find list of events fired throughout Magento2 here