Magento events and observers are a good old way of extending Magento. This approach originated from Magento 1 and is well-known beyond the Magento community and platform. It follows an observer design pattern and has different implementation and variations in different frameworks. This article covers how the Event Framework was implemented in Magento and how it is recommended to be used by the Magento Development Team..
Event Framework in Magento 2 Open Source
The following diagram illustrates the main components of the Magento 2 Event Framework:
Blue color is used for highlighting the main components.
ObserverInterface is an interface to implement for all custom observers that listen to events.
ManagerInterface is responsible for dispatching events and invoking registered observers.
Event Framework in Magento 2 Commerce
It should be noted that this is how the Event Framework functions in Magento 2 Open Source.
Switching to Magento 2 Commerce, Magento 2 Event Framework is changed. Changes come from
Magento_Staging feature which needs to give more extensible points for executing events and observers when it comes to staging update preview mode:
Magento_Staging provides its own implementation of
ManagerInterface component, enabling the ignoring of events or observers during the preview of a staging update.
1. It’s crucial to distinguish the usage of observers in Magento 1, where they were utilized for various manipulations with input event data. By contrast, it’s recommended not to change input event data in M2 observers. Instead, this can be done by using interceptors.
2. Observers should be registered on events that are as specific as possible. This is important from a backend performance perspective. The same rule goes for choosing an area to register observers. For example, registering observers to the global area when they extend functionalities on the Magento Admin side is considered poor practice. Obviously,
adminhtml area would be a better choice. The same goes for observers that should only extend storefront. In this case, they should be declared in
Magento Event Framework is a good and elegant way of extending Magento 2. Hopefully, this article has helped or reminded you how to use it without any doubts.
You may also be interested in: