PHP code example of ttpryg / event-dispatcher

1. Go to this page and download the library: Download ttpryg/event-dispatcher library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ttpryg / event-dispatcher example snippets


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;
    }
}

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", "[email protected]"));
text
event-dispatcher/
├── src/
│   ├── Dispatcher/
│   │   └── EventDispatcher.php
│   ├── Provider/
│   │   └── ListenerProvider.php
│   └── Exceptions/
│       └── InvalidListenerException.php
├── tests/
│   ├── EventDispatcherTest.php
│   └── ListenerProviderTest.php
└── composer.json