PHP code example of memran / marwa-event

1. Go to this page and download the library: Download memran/marwa-event 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/ */

    

memran / marwa-event example snippets


use Marwa\Event\Resolver\ListenerResolver;
use Marwa\Event\Core\ListenerProvider;
use Marwa\Event\Core\EventDispatcher;
use Marwa\Event\Bus\EventBus;

// Bootstrap (no container)
$resolver   = new ListenerResolver();           // optionally pass a PSR-11 container
$provider   = new ListenerProvider($resolver);
$dispatcher = new EventDispatcher($provider);
$bus        = new EventBus($provider, $dispatcher);

// Event
final class UserRegistered extends Marwa\Event\Contracts\StoppableEvent {
    public function __construct(public string $email) {}
}

// Listeners
$bus->listen(UserRegistered::class, function (UserRegistered $e) {
    // send welcome
}, 100);

$bus->listen(UserRegistered::class, [App\Listeners\Audit::class, 'handle'], 0);
$bus->listen(UserRegistered::class, App\Listeners\NotifyAdmin::class); // invokable

// Dispatch
$bus->dispatch(new UserRegistered('[email protected]'));

use Marwa\Event\Contracts\Subscriber;

final class UserSubscriber implements Subscriber
{
    public static function getSubscribedEvents(): array
    {
        return [
            UserRegistered::class => [
                ['welcome', 50],
                ['audit', 0],
            ],
        ];
    }

    public function welcome(UserRegistered $e): void {/* ... */}
    public function audit(UserRegistered $e): void {/* ... */}
}

$bus->subscribe(UserSubscriber::class);

int   EventBus::listen(string $eventClass, callable|string|array $listener, int $priority = 0)
bool  EventBus::forget(int $id)
void  EventBus::subscribe(Subscriber|string $subscriber)
object EventBus::dispatch(object $event)

public function testPriorityOrder(): void
{
    $bus = $this->makeBus();
    $seq = [];

    $bus->listen(MyEvent::class, function () use (&$seq) { $seq[] = 2; }, 0);
    $bus->listen(MyEvent::class, function () use (&$seq) { $seq[] = 1; }, 100);

    $bus->dispatch(new MyEvent());

    $this->assertSame([1, 2], $seq);
}