Hyvä Theme is Now Open Source: What This Means for Magento Community - Mageplaza
Hyvä is now Open Source and free. Discover what changed, what remains commercial, how it impacts the Magento ecosystem, and how to maximize its full potential.
Vinh Jacker | 03-17-2025
Customizing the Magento 2 store is essential for meeting business requirements, and Events and Observers provide a systematic approach to achieve this. By taking advantage of Magento 2 events and observers, you can integrate custom workflows, automate processes, and enhance the user experience without modifying core files. From handling order updates to tracking customer interactions, this guide will show you how to create Magento 2 events & observers.
Magento use area definitions to manage the store. We will have a frontend area and admin area. With the configuration file, they can be put in 3 places:
etc/ folder is the configuration which can be used in both admin and frontend.etc/frontend folder will be used for frontend area.etc/adminhtml folder will be used for admin area.The same with the event configuration file. You can create an event configuration file for each area like this:
app/code/Mageplaza/HelloWorld/etc/adminhtml/events.xmlapp/code/Mageplaza/HelloWorld/etc/frontend/events.xmlapp/code/Mageplaza/HelloWorld/etc/events.xmlNow we want to dispatch an Magento 2 event list which allow other module can change the word displayed. We will change the controller like this:
File: app/code/Mageplaza/HelloWorld/Controller/Index/Test.php
Content would be:
<?php
namespace Mageplaza\HelloWorld\Controller\Index;
class Test extends \Magento\Framework\App\Action\Action
{
public function execute()
{
$textDisplay = new \Magento\Framework\DataObject(array('text' => 'Mageplaza'));
$this->_eventManager->dispatch('mageplaza_helloworld_display_text', ['mp_text' => $textDisplay]);
echo $textDisplay->getText();
exit;
}
}
The dispatch method will receive 2 arguments: an unique event name and an array data. In this example, we add the data object to the event and call it back to display the text.
File: app/code/Mageplaza/HelloWorld/etc/frontend/events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="mageplaza_helloworld_display_text">
<observer name="mp_display_text" instance="Mageplaza\HelloWorld\Observer\ChangeDisplayText" />
</event>
</config>
In this file, under config element, we define an event element with the name of the event dispatch above. The class that will execute this event will be defined in the observer element by an instance attribute. The name of observer is used to identify this with other observers of this event.
With this events.xml file, Magento will execute class Mageplaza\HelloWorld\Observer\ChangeDisplayText whenever the dispatch method of this event was called in frontend area. Please note that we place events.xml in the frontend area, so if you dispatch that event in the admin area (like admin controller), it will not run.
Now we will create a class to execute above event.
File: app/code/Mageplaza/HelloWorld/Observer/ChangeDisplayText.php
<?php
namespace Mageplaza\HelloWorld\Observer;
class ChangeDisplayText implements \Magento\Framework\Event\ObserverInterface
{
public function execute(\Magento\Framework\Event\Observer $observer)
{
$displayText = $observer->getData('mp_text');
echo $displayText->getText() . " - Event </br>";
$displayText->setText('Execute event successfully.');
return $this;
}
}
This class will implement the ObserverInterface and declare the execute method. You can see this simple method to know how it work.
Let’s flush cache and see the result.

Use case: Trigger a custom action when a new order is placed.
Example: Send an order confirmation email with personalized content or additional promotional offers.
Use case: Execute custom code when a new customer registers on the site.
Example: Automatically assign the new customer to a specific group or send a welcome email.
Use case: Perform actions when a product is saved or updated.
Example: Update inventory levels in a third-party system or reindex related data.
Use case: Observe the order placement event.
Example: Send a custom email to the customer or store admin when an order is placed.
Use case: Observe customer login/logout events.
Example: Log these activities to analyze customer behavior and improve the site’s performance.
Use case: Observe product save events.
Example: Update inventory levels in an external warehouse management system.
Optimizing the performance of Magento 2 events and observers is crucial for maintaining a fast and responsive eCommerce store. Here are some tips to help you achieve optimal performance:
Issue: The observer is not being triggered when the event is dispatched.
Troubleshooting: Ensure that the event name is correct and matches the one used in the observer declaration. Check the event configuration in events.xml and confirm that the observer is properly registered.
Issue: The observer receives a null object instead of the expected data.
Troubleshooting: Verify that the event passes the correct data. Check the event declaration and ensure that the data is being dispatched correctly. Make sure the observer is configured to receive the correct parameters.
Issue: The observer is causing performance issues due to heavy processing or database queries.
Troubleshooting: Optimize the observer code by minimizing database queries and using caching where possible. Consider moving heavy processing to asynchronous tasks or background jobs.
Issue: Events are not being dispatched as expected.
Troubleshooting: Check the event dispatching code for errors. Ensure that the event manager is being used correctly and that the event is being dispatched in the right context.
Issue: Multiple observers are conflicting or causing unexpected behavior.
Troubleshooting: Review the order of observer execution and ensure that there are no conflicts. Use priority settings to control the order in which observers are executed. Check for duplicate event registrations.
1. Can I have multiple observers for the same event?
Yes, you can have multiple observers for the same event. Each observer will be executed in the order they are defined in the events.xml file. You can use the sortOrder attribute to control the execution order.
2. How do I debug issues with events and observers?
To debug issues with events and observers, you can use logging to track the flow of execution and identify where things might be going wrong. Additionally, ensure that the event names and observer configurations are correct and check for any typos or errors.
3. How do events and observers affect performance?
Events and observers can impact performance if not used efficiently. It’s important to keep observer logic simple, minimize database queries, use caching, and consider asynchronous processing for heavy tasks.
4. Can I modify event data in an observer?
Yes, you can modify event data in an observer by accessing the event object and updating its values. However, be cautious, as modifying core event data may impact other observers listening to the same event.
5. Can I use events and observers for API requests?
Yes, you can trigger events when an API request modifies data (e.g., a new order is created via API). Observers can then listen for these events and perform additional actions, such as syncing with an external system. To expose your custom logic or data as a service, learn how to create API in Magento 2 and integrate it with events and observers for a complete modular setup.
To sum up, creating events and observers in Magento 2 allows developers to create modular and maintainable code that can adapt to future changes easily. By following the detailed steps in this article, you can ensure that your customizations are efficient, upgrade-safe, and easy to manage in the long run.
Related Post