Jeckel-Lab / command-dispatcher

Command dispatcher pattern implementation
2 stars 1 forks source link

Add documentation #33

Open jeckel opened 2 years ago

jeckel commented 2 years ago

Update readme on how to configure it, and how to use It with DI tools

With PHP/DI

return static function (ContainerBuilder $containerBuilder) {
    $containerBuilder->addDefinitions(
        [
            'command-handlers' => [
                ActivateUserHandler::class,
                CreateUserHandler::class,
            ],
            LoggerInterface::class => DI\autowire(Logger::class),
            CommandBus::class => function(ContainerInterface $container) {
                /** @var array<class-string<CommandHandler<Command>>> $handlers */
                $handlers = $container->get('command-handlers');
                return (new CommandBusBuilder($container))
                    ->addCommandHandler(...$handlers)
                    ->addDecorator(LoggerDecorator::class)
                    ->build();
            },
        ]
    );
};
jeckel commented 2 years ago

Documentation for obsolete CommandBus:

Simple and optimized command-bus implementation

Warning, this package is still a Work in progress

Installation

Require: php >= 8.0

Install it via composer

composer require jeckel-lab/command-bus

Usage

Initialisation

The best way to start is by using the CommandBusBuilder:

use JeckelLab\CommandBus\CommandBus\CommandBusBuilder;

/**
 * @var Psr\ContainerInterface $container
 */
$build = new CommandBusBuilder($container);

Then you can register your command handlers. Each handler should implement the CommandHandler interface.

// All command handler should implement the `CommandHandler` interface
$builder->addHandler(
    FirstCommandHandler::class,
    SecondCommandHandler::class
);

$builder->addHandler(
    ThridCommandHandler::class
)

Then you can also add some decorators to the bus. Decorators should implement the CommandBusDecorator interface, and it's suggest to extend directly the AbstractCommandBusDecorator class.

$builder->addDecorator(new SimpleCommandBusDecorator());

Finally, just build the command bus:

$commandBus = $builder->build();

Use it

When command bus is correctly build, it's easy to use it:

/** @var CommandResponse $response */
$response = $commandBus->dispatch(new MyCommand());