telephantast/message-bus

Thesis Message Bus

0.2.x-dev 2025-04-05 21:25 UTC

This package is auto-updated.

Last update: 2025-04-05 21:26:13 UTC


README

PHP Version Requirement GitHub Release Code Coverage Mutation testing badge

Installation

composer require thesis/message-bus

Quick Start

use Thesis\Message\Command;
use Thesis\Message\Event;
use Thesis\Message\Message;
use Thesis\MessageBus\MessageBus;
use Thesis\MessageBus\Handler\ArrayHandlerRegistry;
use Thesis\MessageBus\Handler\CallableHandler;
use Thesis\MessageBus\Context;

// First, declare a bunch of messages.

final readonly class RegisterUser implements Command
{
    public function __construct(
        public string $nickname,
        public string $firstName,
    ) {}
}

final readonly class UserRegistered implements Event
{
    public function __construct(
        public string $nickname,
    ) {}
}

/**
 * @implements Message<string>
 */
final readonly class GetUserName implements Message
{
    public function __construct(
        public string $nickname,
    ) {}
}

// Then assemble a simple synchronous MessageBus.

$firstNames = [];

$messageBus = new MessageBus(
    handlerRegistry: new ArrayHandlerRegistry([
        RegisterUser::class => new CallableHandler(
            handler: function (RegisterUser $command, Context $context) use (&$firstNames): void {
                $firstNames[$command->nickname] = $command->firstName;

                $context->dispatch(new UserRegistered($command->nickname));
            },
        ),
        UserRegistered::class => new CallableHandler(
            handler: function (UserRegistered $event): void {
                echo "User {$event->nickname} has just registered!\n";
            },
        ),
        GetUserName::class => new CallableHandler(
            handler: function (GetUserName $query) use (&$firstNames): string {
                return $firstNames[$query->nickname];
            },
        ),
    ]),
);

// Give it a try!

$messageBus->dispatch(new RegisterUser('vudaltsov', 'Valentin'));

$firstName = $messageBus->dispatch(new GetUserName('vudaltsov'));

echo "Get acquainted with {$firstName}!\n";