API Reference

Class and method documentation for WPZylos Events.


EventDispatcher

WPZylos\Framework\Events\EventDispatcher

PSR-14 compliant event dispatcher. Dispatches events to listeners retrieved from the injected ListenerProviderInterface.

Implements: Psr\EventDispatcher\EventDispatcherInterface

Constructor

public function __construct(Psr\EventDispatcher\ListenerProviderInterface $listenerProvider)
ParameterTypeDescription
$listenerProviderListenerProviderInterfaceProvider that supplies listeners for events

Methods

MethodReturnsDescription
dispatch(object $event): objectobjectDispatches the event to all listeners returned by the provider. Returns the (possibly modified) event object.

Note: EventDispatcher has only the dispatch() method. Listener registration is handled by ListenerProvider. There is no listen(), addSubscriber(), removeListener(), or getListeners() method on this class.

Propagation Stopping

If the event implements Psr\EventDispatcher\StoppableEventInterface, the dispatcher checks isPropagationStopped() before calling each listener. Once stopped, remaining listeners are skipped.

Example

use WPZylos\Framework\Events\EventDispatcher;
use WPZylos\Framework\Events\ListenerProvider;

$provider   = new ListenerProvider();
$dispatcher = new EventDispatcher($provider);

$provider->addListener(UserCreated::class, function (UserCreated $event) {
    // Handle user creation
});

$event = $dispatcher->dispatch(new UserCreated($user));

ListenerProvider

WPZylos\Framework\Events\ListenerProvider

Manages event listener registration and retrieval with priority support.

Implements: Psr\EventDispatcher\ListenerProviderInterface

Methods

MethodReturnsDescription
addListener(string $eventClass, callable $listener, int $priority = 10): staticstaticRegister a listener for an event type. Lower priority values execute earlier. Returns $this for chaining.
getListenersForEvent(object $event): iterableiterable<callable>Returns all listeners for the event, sorted by priority. Includes listeners registered for parent classes and implemented interfaces.
clearListeners(string $eventClass): staticstaticRemoves all listeners for the given event class. Returns $this for chaining.
hasListeners(string $eventClass): boolboolReturns true if any listeners are registered for the given event class.

Note: There is no removeListener() method. To remove listeners for an event class, use clearListeners() which removes all listeners for that class at once.

Priority

Listeners are sorted by priority (ascending). Lower values run first:

PriorityExecution Order
1Runs first
10Default
100Runs last

Hierarchical Matching

getListenersForEvent() returns listeners registered for:

  1. The exact class of the event
  2. Any parent class in the inheritance chain
  3. Any interface the event implements

Example

use WPZylos\Framework\Events\ListenerProvider;

$provider = new ListenerProvider();

// Register with default priority (10)
$provider->addListener(OrderPlaced::class, function (OrderPlaced $event) {
    // Handle order
});

// Register with higher priority (runs first)
$provider->addListener(OrderPlaced::class, $validateStock, 1);

// Fluent chaining
$provider
    ->addListener(UserCreated::class, $sendWelcomeEmail)
    ->addListener(UserCreated::class, $logCreation, 5);

// Check and clear
$provider->hasListeners(OrderPlaced::class); // true
$provider->clearListeners(OrderPlaced::class);
$provider->hasListeners(OrderPlaced::class); // false

StoppableEvent

WPZylos\Framework\Events\StoppableEvent

Abstract base class for events that can have their propagation stopped. Extend this class instead of implementing StoppableEventInterface manually.

Type: abstract classImplements: Psr\EventDispatcher\StoppableEventInterface

Methods

MethodReturnsDescription
stopPropagation(): voidvoidStops event propagation. No further listeners will be called.
isPropagationStopped(): boolboolReturns true if propagation has been stopped.

Note: This is an abstract class, not a trait or interface. Your event classes should extend it.

Example

use WPZylos\Framework\Events\StoppableEvent;

class PaymentValidation extends StoppableEvent
{
    public bool $isValid = true;

    public function __construct(
        public readonly Payment $payment
    ) {}

    public function markInvalid(): void
    {
        $this->isValid = false;
        $this->stopPropagation(); // Stops further listeners
    }
}

EventSubscriberInterface

WPZylos\Framework\Events\EventSubscriberInterface

Interface for classes that subscribe to multiple events. Subscribers declare all their event-to-method mappings in a single static method.

Methods

MethodReturnsDescription
static getSubscribedEvents(): arrayarrayReturns an event-to-handler mapping.

Return Format

The getSubscribedEvents() method supports three mapping formats:

return [
    // Format 1: Simple — event maps to a method name (default priority 10)
    UserCreated::class => 'onUserCreated',

    // Format 2: With priority — event maps to [method, priority]
    UserUpdated::class => ['onUserUpdated', 5],

    // Format 3: Multiple handlers — event maps to array of [method, priority] pairs
    OrderPlaced::class => [
        ['onOrderPlaced', 1],
        ['sendConfirmation', 20],
    ],
];

Example

use WPZylos\Framework\Events\EventSubscriberInterface;

class UserEventSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            UserCreated::class => 'onUserCreated',
            UserDeleted::class => ['onUserDeleted', 5],
        ];
    }

    public function onUserCreated(UserCreated $event): void
    {
        // Handle user creation
    }

    public function onUserDeleted(UserDeleted $event): void
    {
        // Handle user deletion
    }
}

EventServiceProvider

WPZylos\Framework\Events\EventServiceProvider

Service provider that registers the event system into the WPZylos application container.

Extends: WPZylos\Framework\Core\ServiceProvider

Container Bindings

All bindings are registered as singletons (one shared instance):

BindingResolves ToDescription
ListenerProvider::classListenerProviderConcrete listener provider instance
Psr\EventDispatcher\ListenerProviderInterfaceListenerProviderPSR-14 listener provider interface
EventDispatcher::classEventDispatcherConcrete event dispatcher instance
Psr\EventDispatcher\EventDispatcherInterfaceEventDispatcherPSR-14 event dispatcher interface
'events'EventDispatcherString alias for convenience access

Methods

MethodReturnsDescription
register(ApplicationInterface $app): voidvoidRegisters all container bindings. Called automatically by the application.
subscribe(EventSubscriberInterface $subscriber): voidvoidRegisters all listeners defined by a subscriber's getSubscribedEvents() method.

Example

// Register a subscriber through the service provider
$eventProvider = $app->make(EventServiceProvider::class);
$eventProvider->subscribe(new UserEventSubscriber());