Skip to content

Repository files navigation

Quillstack Events

Tests

An event dispatcher based on PSR-14: Event Dispatcher.

Installation

composer require quillstack/events

Usage

An event is any object. A listener is anything callable which takes it:

use Quillstack\Events\EventDispatcher;
use Quillstack\Events\ListenerProvider;

$listeners = new ListenerProvider();
$listeners->listen(UserRegistered::class, function (UserRegistered $event) {
    $this->mailer->welcome($event->email);
});

$dispatcher = new EventDispatcher($listeners);
$dispatcher->dispatch(new UserRegistered('radek@quillstack.com'));

dispatch() gives the event back, so a listener can answer through it.

Order

Listeners with a higher priority are called first, and two of the same priority are called in the order they were registered:

$listeners->listen(UserRegistered::class, $writeToTheLog, 10);
$listeners->listen(UserRegistered::class, $sendTheEmail);
$listeners->listen(UserRegistered::class, $cleanUpAfterwards, -10);

Listening for a family of events

A listener registered for a class is called for that class and for anything extending or implementing it, so listening for an interface catches every event carrying it:

$listeners->listen(HasUser::class, $recordWhoDidIt);

Calling an end to an event

An event extending StoppableEvent can be stopped by a listener, and the ones after it are not called:

final class OrderPlaced extends StoppableEvent
{
}

$listeners->listen(OrderPlaced::class, function (OrderPlaced $event) {
    if ($this->alreadyHandled($event)) {
        $event->stopPropagation();
    }
});

Tests

composer test

Coverage needs phpdbg:

composer test:coverage

License

MIT. See LICENSE.

About

An event dispatcher based on PSR-14: Event Dispatcher.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages