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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Sorting listeners by priority once at registration keeps dispatch fast and deterministic.
- 2Returning a value from a listener lets handlers transform the payload as it flows through the chain.
- 3A false return gives any listener the power to short-circuit the remaining handlers.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
php
<?php final class RotatingFileLogger {
How a rotating file logger works in PHP
logging
file-rotation
io
Intermediate
9 steps
php
class TwoFactorController extends Controller { public function show(Request $request): View|RedirectResponse {
Two-factor auth challenge flow in Laravel
authentication
two-factor
middleware
Intermediate
10 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-priority-event-dispatcher-in-php-explained-php-e725/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.