Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 42 ยท Plugins and Events

Events and Observers

Learn how Magento dispatches events, how to declare an observer in events.xml, how areas change which observers run, and when to use a plugin instead.

Magento code constantly announces what it is doing. When a customer logs in, when a product is saved, when an order is placed, the framework dispatches an event: a named message with some data attached. Any module can listen for that name and run its own code. The listener is called an observer.

Events are the loosest way to extend Magento. The code that dispatches the event does not know who listens, and your observer does not change the dispatching class at all. In this lesson you will see how events are dispatched, how an observer is declared in events.xml, how areas limit where an observer runs, and how to choose between an observer and a plugin. Magento itself cannot run on this site, so the real PHP and XML are read-only, and the runnable examples are plain-PHP stand-ins that follow the same idea.

Dispatching an event

The class that announces something uses the event manager. In real Magento you inject Magento\Framework\Event\ManagerInterface through the constructor (see The Object Manager and Constructor Injection) and call dispatch() with an event name and an array of data:

PHP
<?php

namespace Acme\Shipping\Model;

use Magento\Framework\Event\ManagerInterface;

class LabelPrinter
{
    public function __construct(private ManagerInterface $eventManager)
    {
    }

    public function print(string $orderId): void
    {
        // ... create the label ...
        $this->eventManager->dispatch('acme_shipping_label_printed', [
            'order_id' => $orderId,
        ]);
    }
}

The array keys become data on the event object. A listener reads them with $observer->getEvent()->getOrderId() or $observer->getData('order_id'). You do not need to register an event name anywhere: an event exists the moment someone dispatches it. A good habit is to prefix names with your vendor and module (acme_shipping_label_printed) so they never clash with core events.

Many core models dispatch events for you. A model that extends AbstractModel has an event prefix, and saving it dispatches <prefix>_save_before and <prefix>_save_after, plus the generic model_save_before and model_save_after. Product saves, for example, are announced as catalog_product_save_after. Controllers also dispatch events around every request, and layout generation does too.

Declaring an observer in events.xml

To listen, you do two things: write a class and declare it in an events.xml file inside your module's etc folder.

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="acme_shipping_label_printed">
        <observer name="acme_notify_warehouse"
                  instance="Acme\Shipping\Observer\NotifyWarehouse"/>
    </event>
</config>

The event node names the event. Inside it, each observer has a unique name (unique within that event) and an instance, the class to run. The class implements ObserverInterface:

PHP
<?php

namespace Acme\Shipping\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Psr\Log\LoggerInterface;

class NotifyWarehouse implements ObserverInterface
{
    public function __construct(private LoggerInterface $logger)
    {
    }

    public function execute(Observer $observer): void
    {
        $orderId = $observer->getEvent()->getData('order_id');
        $this->logger->info('Label printed for order ' . $orderId);
    }
}

There is exactly one method, execute(). It receives an Observer object that wraps the event and its data. The return value is ignored. Observers are created by the object manager, so constructor injection works as it does everywhere else.

Two attributes are worth knowing. disabled="true" on an observer switches it off, which is how one module turns off an observer declared by another. Because XML files are merged, you redeclare the same event and observer name in your own module and add the attribute. The name therefore acts as the identity used for merging and overriding.

flowchart LR
    A["Code calls<br/>dispatch('event', data)"] --> B["Event manager"]
    B --> C["Reads merged events.xml<br/>for this area"]
    C --> D["Observer 1: execute()"]
    C --> E["Observer 2: execute()"]
    D --> F["Dispatcher continues"]
    E --> F

The dispatcher does not know who listens. The event manager looks up the observers in the merged configuration and calls each one in turn.

Areas decide where an observer runs

You met areas in Areas and Configuration Files. Events follow the same rule. There are three common places for events.xml:

File Runs for
etc/events.xml Every area (global)
etc/frontend/events.xml The storefront only
etc/adminhtml/events.xml The admin panel only

Prefer the narrowest file that works. An observer that only matters in the storefront belongs in etc/frontend/events.xml. That keeps it out of admin requests and out of API calls, which saves work and avoids surprising side effects. Use the global file only when the event can truly happen anywhere, such as an order being placed through the storefront, the admin, or the REST API.

Some events you will meet

The exact event list depends on your Magento version, so confirm a name in the source before relying on it. These are long-standing ones:

  • controller_action_predispatch and controller_action_postdispatch, around every controller action, with route-specific variants that add the route name to the end.
  • catalog_product_save_before and catalog_product_save_after, around saving a product.
  • customer_login and customer_logout, when a customer signs in or out.
  • sales_order_place_after, after an order object has been placed.
  • checkout_submit_all_after, near the end of checkout submission.

To find events in your own installation, search the code for ->dispatch(. Because event names are strings, a project-wide search is the reliable way to discover what you can hook into.

Observers or plugins?

Both extend behavior without editing core files. They are different tools.

Observer Plugin
Hooks into An event someone chose to dispatch Any public method of a class
Can change arguments or return values Only by modifying objects it receives Yes, directly
Can stop the original code No Yes, with an around plugin
Needs the author to cooperate Yes, an event must exist No

Use an observer when you want to react to something that happened: write a log entry, call another system, update a related record. Use a plugin when you need to change how a specific method behaves. Observers are also safer when several modules are involved, because they cannot short-circuit one another. For more on plugin ordering and its traps, see Plugin Best Practices and Pitfalls.

Some practical rules for observers:

  • Keep them fast. An observer on catalog_product_save_after runs on every product save. Heavy work belongs in a queue (see Cron Jobs and Message Queues).
  • Do not depend on order. Observers for the same event run in an order you should treat as unspecified.
  • Do not catch the whole world. If your observer throws, the exception travels back into the code that dispatched the event and can break checkout. Handle expected failures yourself and log them.
  • Do not try to return data. If you need a result, a plugin or a service contract fits better.

Try it: a mini event manager

This stand-in is not Magento's EventManager, but it follows the same shape: a configuration array like merged events.xml data, per-area files, a disabled flag, and observers that receive an Observer object wrapping the event. Real Magento reads the configuration from XML and builds observers through the object manager.

PHP Dispatching events to observers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The frontend request runs three observers (two global, one from the frontend file); the admin request runs only the two global ones. Redeclaring acme_audit with disabled replaces the earlier entry, which mirrors how Magento merges events.xml files from different modules.

Here is a second stand-in. Core models announce their own saves with a prefix, so one save produces both a specific and a generic event. This sketch imitates that naming pattern, nothing more.

PHP Model save events with an event prefix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The generic model_save_after listener fires for every model, which shows why such listeners must be cheap and must check what they received. The specific listener only hears products.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where do you declare that a class should observe an event?

    Observers are declared in events.xml, either global (etc/events.xml) or per area (for example etc/frontend/events.xml).
  2. 2. What does an observer's execute() method return?

    The dispatcher does not use what an observer returns. If you need to change a method's result, use a plugin.
  3. 3. You only need your code on storefront requests. Which file fits best?

    Area-specific files limit where the observer runs. The frontend file keeps it out of admin and API requests.
  4. 4. When is a plugin a better choice than an observer?

    Observers can only react to events that someone dispatched. Plugins hook any public method and can change its inputs and outputs.

Summary

  • Code announces events with dispatch($name, $data); any module can listen without changing the dispatcher.
  • An observer is a class implementing ObserverInterface with one execute(Observer $observer) method, declared in events.xml.
  • Global, frontend and adminhtml files decide in which area the observer runs; choose the narrowest.
  • disabled="true" plus the same observer name lets one module switch off another's observer.
  • Models dispatch <prefix>_save_before/after and generic model_save_* events.
  • Use observers to react; use plugins to change behavior. Keep observers fast and never rely on their order.

Next, follow a web request into your module in Routing and Controllers.