Lab 13: Event-Driven PHP

Time: 40 minutes | Level: Advanced | Docker: docker run -it --rm php:8.3-cli bash

PSR-14 defines a standard event dispatching interface. This lab implements a PSR-14 compliant dispatcher from scratch, adds event subscribers, and explores async event patterns with Symfony Messenger concepts.


Step 1: PSR-14 Interfaces

PSR-14 defines two core interfaces: EventDispatcherInterface and ListenerProviderInterface.

<?php
// PSR-14 interfaces (simplified β€” use psr/event-dispatcher in real projects)

interface StoppableEventInterface {
    public function isPropagationStopped(): bool;
}

interface ListenerProviderInterface {
    public function getListenersForEvent(object $event): iterable;
}

interface EventDispatcherInterface {
    public function dispatch(object $event): object;
}

// Verify interfaces
echo "PSR-14 interfaces defined\n";
$interfaces = ['StoppableEventInterface', 'ListenerProviderInterface', 'EventDispatcherInterface'];
foreach ($interfaces as $iface) {
    echo "  βœ“ $iface\n";
}

πŸ“Έ Verified Output:


Step 2: Implementing a PSR-14 Dispatcher

πŸ“Έ Verified Output:


Step 3: Stoppable Events

πŸ“Έ Verified Output:


Step 4: Event Subscribers

πŸ“Έ Verified Output:


Step 5: Async Event Handling Concept

πŸ“Έ Verified Output:


Step 6: Symfony Messenger Concepts

πŸ“Έ Verified Output:


Step 7: Event Middleware Pipeline

πŸ“Έ Verified Output:


Step 8: Capstone β€” Full Event System

πŸ“Έ Verified Output:


Summary

Concept
Interface/Class
PSR

Event dispatcher

EventDispatcherInterface::dispatch()

PSR-14

Listener provider

ListenerProviderInterface::getListenersForEvent()

PSR-14

Stoppable events

StoppableEventInterface::isPropagationStopped()

PSR-14

Subscriber pattern

getSubscribedEvents(): array

Convention

Async queue

MessageBus + transport

Symfony Messenger

Event middleware

Pipeline::use(callable $mw)

Custom pattern

Priority listeners

Provider sorts by priority

Implementation detail

Message handlers

__invoke(SpecificMessage $msg)

Symfony convention

Last updated