Magento events and observers are a good old way of extending Magento. They came from Magento 1, but an approach 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 Event Framework was implemented in Magento and how it’s suggested to be using by Magento Development Team.

Event Framework in Magento 2 Open Source

Following diagram shows main components of Magento 2 Event Framework:

Magento 2 Event Framework Diagram

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’s needed to say that this is how Event Framework works 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 2 Event Framework in Commerce

Magento_Staging provides own implementation of ManagerInterface component which enables ignoring events or observers if staging update is being previewed.

Best Practices

1. It’s important not to be confused by the usage of observers in Magento 1 where they were used for all kind of 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 in terms of backend performance side. The same rule goes for choosing an area to register observers. For example, it’s poor practice to register observers to the global area when they are extending stuff on Magento Admin side. 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 frontend area.

Final thoughts

Magento Event Framework is a good and elegant way of extending Magento 2. Hopefully, this article helps or reminds you how to use it without any doubts.

You may also be interested in:

Event system in Magento 1 vs. Magento 2
Choose your perfect Event in Magento 2
Magento DevDocs – Technical guidelines