php 42 lines · 8 steps

A priority event dispatcher in PHP

A small event bus that registers prioritized listeners and threads a payload through them until one halts the chain.

Explained by highlit
1<?php
2 
3namespace App\Events;
4 
5class EventDispatcher
6{
7 private array $listeners = [];
8 
9 public function listen(string $event, callable $listener, int $priority = 0): void
10 {
11 $this->listeners[$event][] = ['callback' => $listener, 'priority' => $priority];
12 
13 usort($this->listeners[$event], static fn ($a, $b) => $b['priority'] <=> $a['priority']);
14 }
15 
16 public function dispatch(string $event, mixed $payload = null): mixed
17 {
18 foreach ($this->listeners[$event] ?? [] as $listener) {
19 $result = ($listener['callback'])($payload, $event);
20 
21 if ($result === false) {
22 break;
23 }
24 
25 if ($result !== null) {
26 $payload = $result;
27 }
28 }
29 
30 return $payload;
31 }
32 
33 public function forget(string $event): void
34 {
35 unset($this->listeners[$event]);
36 }
37 
38 public function hasListeners(string $event): bool
39 {
40 return !empty($this->listeners[$event]);
41 }
42}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Sorting listeners by priority once at registration keeps dispatch fast and deterministic.
  2. 2Returning a value from a listener lets handlers transform the payload as it flows through the chain.
  3. 3A false return gives any listener the power to short-circuit the remaining handlers.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A priority event dispatcher in PHP — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code