Skip to content
Tutorials Center
My learning

Topics

Lesson 116 of 147 ยท Advanced PHP

Events and Listeners

Learn the observer pattern in PHP and build a PSR-14 style event dispatcher with listeners, priorities, stoppable events and subscribers.

When a user registers, several things should happen: send a welcome email, create a default workspace, record an analytics event. The naive approach is to call all three from the registration code. Then the registration code knows about email, workspaces and analytics, and every new reaction means editing it again.

Events invert that. The registration code announces "a user registered" and carries on. Anyone interested listens for that announcement. This is the observer pattern, and PHP has a standard for it, PSR-14, used by Symfony, Laravel (with its own flavor), Laminas and many libraries. In this lesson you will build the pieces: an event, listeners, and a dispatcher, and then add priorities and a way to stop propagation.

You should be comfortable with interfaces, closures and the observer sketch in design patterns. Wiring the dispatcher into services is easiest with dependency injection.

Vocabulary

  • An event is a plain object describing something that happened, named in the past tense: UserRegistered, OrderShipped. It carries the data listeners need.
  • A listener is any callable that accepts the event.
  • A dispatcher holds the listeners and, given an event, calls every listener interested in it.
  • An event provider is the part of the dispatcher that answers "which listeners match this event?" PSR-14 separates it from the dispatcher; we will keep both in one class for simplicity.
sequenceDiagram
    participant S as RegistrationService
    participant D as Dispatcher
    participant M as WelcomeEmail listener
    participant A as Analytics listener
    S->>D: dispatch(UserRegistered)
    D->>M: __invoke(event)
    D->>A: __invoke(event)
    D-->>S: the same event object

The service knows only the dispatcher; the dispatcher knows which listeners to call.

The simplest dispatcher

PSR-14's key trick is that the class of the event is its name. A listener registered for UserRegistered::class is called for that class and also for any parent class or interface, because of instanceof. Here is a minimal dispatcher:

PHP A minimal event dispatcher

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.

register() never mentions email or analytics. Adding a third reaction means calling listen() once, with no change to registration. Returning the event from dispatch() is part of the PSR-14 contract, because listeners may have changed it.

Listeners that change the event

Events can be mutable on purpose. A classic use is a "can I do this?" hook: listeners add reasons to block an action, or modify data before it is saved. The caller reads the event after dispatch.

Then there is stopping propagation. PSR-14 defines StoppableEventInterface with isPropagationStopped(); the dispatcher checks it before each listener. Let us add that, plus priorities (higher number runs first), which matter when order does:

PHP Priorities and stoppable events

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 audit listener (priority 100) always runs first. For 90,000 cents the limit listener rejects the event, propagation stops, and "reserving stock" is never printed. Generators with yield from keep the listener lookup lazy and simple.

Subscribers: one class, many events

Registering twenty closures by hand gets noisy. A common refinement is a subscriber (or listener class): one class that declares which events it handles.

PHP A subscriber class

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.

Frameworks go one step further and let you tag listener classes with attributes, such as #[AsEventListener], so the wiring is discovered automatically.

Design advice

  • Name events in the past tense and make them small value objects. Data in, no behavior.
  • Listeners should not depend on each other's order. If they must, use priorities sparingly and document why.
  • Events are synchronous by default. A slow listener slows the request. Push heavy work to a queue from inside the listener.
  • Handle failures. If one listener throws, the rest do not run unless you catch. Decide whether a failing analytics call should break registration (usually not).
  • Don't overuse them. An event hides the call path: reading the code, you can't see who reacts. Use events for real extension points and cross-module notifications, not for every method call.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In a PSR-14 style dispatcher, how are listeners selected for an event?

    The event's type acts as its name, and instanceof matching lets a listener for an interface receive every event implementing it.
  2. 2. What happens when a listener marks a stoppable event as propagation stopped?

    Before each listener the dispatcher checks isPropagationStopped(); once true, it returns the event without calling the rest.
  3. 3. Why does dispatch() return the event?

    Mutable events let listeners add data or reasons for rejection; the caller inspects the returned object.
  4. 4. A listener sends a welcome email over a slow network. What is a good approach?

    Events run synchronously in the request. Queueing the slow work keeps the response fast.

Summary

  • An event is a small object describing something that happened; listeners react without the publisher knowing them.
  • A dispatcher finds listeners by the event's class (and parents/interfaces) and calls them in order.
  • PSR-14 events can be stoppable, and dispatchers commonly support priorities.
  • Subscribers group several handlers in one class.
  • Events run synchronously: queue slow work, handle listener failures, and don't hide ordinary calls behind events.

Next: Logging with PSR-3