PHP code example of zorachka / event-dispatcher

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

    

zorachka / event-dispatcher example snippets




declare(strict_types=1);

namespace YourProject\Domain;

use Zorachka\EventDispatcher\EventRecordingCapabilities;

final class Post
{
    use EventRecordingCapabilities; // use trait to register and release events

    private function __construct(private PostId $id)
    {
    }

    public static function create(PostId $id): self
    {
        $self = new self($id);
        $self->registerThat(PostWasCreated::withId($id)); // register event

        return $self;
    }
}




declare(strict_types=1);

mutablePrioritizedListenerProvider;
use Zorachka\EventDispatcher\ListenerPriority;
use Zorachka\EventDispatcher\PrioritizedListenerProvider;
use Zorachka\EventDispatcher\SyncEventDispatcher;

use YourProject\Domain\Post;
use YourProject\Domain\PostId;
use YourProject\Domain\PostWasCreated;
use YourProject\Application\SendEmailToModerator;

use YourProject\Domain\UserWasRegistered;
use YourProject\Application\SendWelcomeEmail;

$registry = new ImmutablePrioritizedListenerProvider([
    new PrioritizedListenerProvider(PostWasCreated::class, [
        ListenerPriority::NORMAL => new SendEmailToModerator(),
    ]),
    new PrioritizedListenerProvider(UserWasRegistered::class, [
        ListenerPriority::NORMAL => new SendWelcomeEmail(), 
    ]),
]);
$dispatcher = new SyncEventDispatcher($registry);

// And in your application use case:

$post = Post::create(
    PostId::fromString('00000000-0000-0000-0000-000000000000')
);

foreach ($post->releaseEvents() as $event) {
    $dispatcher->dispatch($event);
}


use Zorachka\EventDispatcher\EventDispatcherConfig;
use YourProject\Domain\UserWasRegistered;
use YourProject\Application\SendEmailToModerator;

$config = EventDispatcherConfig::withDefaults()
    ->addEventListener(UserWasRegistered::class, SendEmailToModerator::class)
    ->listeners();

use Zorachka\EventDispatcher\EventDispatcherConfig;
use Zorachka\EventDispatcher\ListenerPriority;
use YourProject\Application\SendEmailToModerator;
use YourProject\Domain\UserWasRegistered;

$config = EventDispatcherConfig::withDefaults()
    ->addEventListener(UserWasRegistered::class, SendEmailToModerator::class, ListenerPriority::HIGH)
    ->listeners();