Events and observers design pattern is one of the many design patterns implemented in Magento 2 which helps to extend core functionalities. Events and observers design pattern is based on publish-subscribe pattern .
So, basically to work with this design pattern, we have a configuration file named events.xml . Observer is the class which observes particular event to trigger for its execution, therefore, we need to define the event name in the event node and the observing class name in observer node in events.xml file.
<event name="sales_quote_save_after">
<observer name="set_checkout_quote_id" instance="Magento\Checkout\Observer\SalesQuoteSaveAfterObserver" />
</event>
We can use the already dispatched events of core classes and can also dispatch our custom events. For more, check the official devdoc here.
IMPLEMENTATION
Now we will see, how this design pattern is implemented in Magento 2 codebase.
Events in Magento are dispatched like this -
// var \Magento\Framework\Event\Manager
$this->eventManager->dispatch('my_module_event_before');
This dispatch method is the main entry point. Let's look at the dispatch method -
The dispatch method collects all the observers class defined in events.xml using getObservers() method, and passes observer class in the invoker's dispatch() method one by one, where it checks two things -
The observer is disabled or not (disabled attribute can be used in the events.xml for this purpose)
Whether to use singleton or transient object of the observer class (shared attribute can be used in the events.xml for this purpose)
After that, the execute method of the observer class is called in the _callObserverMethod() like below and the execution control comes to our observer class.
$object->execute($observer);
This is how events and observers design pattern is implemented in Magento 2.
Happy coding :)
留言