Event & Observer in Magento 2
What is an Event in Magento 2?
An Event in Magento 2 is a signal that something has happened in the system. Magento dispatches events at specific points during execution, allowing other modules to react to those events.
This mechanism enables modules to communicate with each other without tightly coupling their code.
What is an Observer?
An Observer is a class that listens for a specific event and executes custom logic when that event is triggered.
Observers implement the ObserverInterface and define the logic that should run when the event occurs.
Why Magento uses Event-Observer Pattern
The Event-Observer pattern provides a flexible way to extend Magento functionality.
- Loose coupling between modules.
- Allows modules to react to system events.
- Improves extensibility.
- Reduces the need to override core classes.
How Event-Observer Works
- An event is dispatched somewhere in Magento code.
- Magento checks if any observers are registered for that event.
- If observers exist, Magento executes them.
- Each observer performs its custom logic.
Example: Dispatching an Event
Magento dispatches events using the event manager.
Example: Register an Observer
To listen to an event, we must register an observer in events.xml.
(File: app/code/VendorName/ModuleName/etc/frontend/events.xml)
Example: Create an Observer Class
The observer class contains the logic that runs when the event is triggered.
(File: app/code/VendorName/ModuleName/Observer/CustomObserver.php)
Scopes of events.xml
Magento allows event observers to be defined in different scopes depending on where they should execute.
- etc/events.xml → Global scope.
- etc/frontend/events.xml → Frontend only.
- etc/adminhtml/events.xml → Admin area only.
Common Magento Events
- sales_order_place_after
- catalog_product_save_after
- checkout_cart_product_add_after
- customer_login
Best Practices
- Use observers when you need to react to Magento events.
- Avoid placing heavy business logic inside observers.
- Use meaningful observer names.
- Keep observer classes lightweight and focused.