Search by

ttpryg / event-dispatcher

totoprayogo1916

PSR-14 Compliant Event Dispatcher & Listener Provider standalone PHP 8.1+ library

Package info

github.com/ttpryg/event-dispatcher

pkg:composer/ttpryg/event-dispatcher

Statistics

Installs: 226

Dependents: 8

Suggesters: 0

Stars: 0

Open Issues: 0

1.0.0 2026-09-21 14:33 UTC

This package is auto-updated.

Last update: 2026-09-21 14:35:29 UTC


README

A lightweight, PSR-14 compliant Event Dispatcher & Listener Provider for PHP 8.1+.

๐ŸŒŸ Key Features

  • PSR-14 Compliant: Fully compatible with PSR-14 contracts (EventDispatcherInterface, ListenerProviderInterface, StoppableEventInterface).
  • Framework Agnostic: Clean, decoupled design that works in any PHP application or framework.
  • Stoppable Events Support: Safely halt propagation chains when isPropagationStopped() returns true.
  • Strictly Typed: Built with modern PHP 8.1+ features (readonly properties, strict types).

๐Ÿ“ฆ Installation

Install the package via Composer:

composer require ttpryg/event-dispatcher

Requirements: PHP 8.1 or higher.

๐Ÿš€ Quick Start

1. Define an Event

namespace App\Event;

use Psr\EventDispatcher\StoppableEventInterface;

class UserRegisteredEvent implements StoppableEventInterface
{
    private bool $stopped = false;

    public function __construct(
        public readonly string $userId,
        public readonly string $email
    ) {}

    public function isPropagationStopped(): bool
    {
        return $this->stopped;
    }

    public function stopPropagation(): void
    {
        $this->stopped = true;
    }
}

2. Register Listeners & Dispatch

use Ttpryg\EventDispatcher\Provider\ListenerProvider;
use Ttpryg\EventDispatcher\Dispatcher\EventDispatcher;
use App\Event\UserRegisteredEvent;

// 1. Initialize Listener Provider
$provider = new ListenerProvider();

// Register listener (Closure or callable)
$provider->addListener(UserRegisteredEvent::class, function (UserRegisteredEvent $event) {
    echo "Welcome email sent to: " . $event->email;
});

// 2. Initialize Dispatcher & Dispatch Event
$dispatcher = new EventDispatcher($provider);
$dispatcher->dispatch(new UserRegisteredEvent("usr_101", "user@example.com"));

๐ŸŒณ Architecture

event-dispatcher/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ Dispatcher/
โ”‚   โ”‚   โ””โ”€โ”€ EventDispatcher.php
โ”‚   โ”œโ”€โ”€ Provider/
โ”‚   โ”‚   โ””โ”€โ”€ ListenerProvider.php
โ”‚   โ””โ”€โ”€ Exceptions/
โ”‚       โ””โ”€โ”€ InvalidListenerException.php
โ”œโ”€โ”€ tests/
โ”‚   โ”œโ”€โ”€ EventDispatcherTest.php
โ”‚   โ””โ”€โ”€ ListenerProviderTest.php
โ””โ”€โ”€ composer.json

๐Ÿงช Testing

Run the test suite using PHPUnit:

composer test
# or
./vendor/bin/phpunit

๐Ÿ“„ License

This project is open-sourced software licensed under the MIT License.