blacksmith-project / command-bus
A PHP Library
v0.5.0
2019-10-03 04:27 UTC
Requires
- php: ^7.3
Requires (Dev)
- escapestudios/symfony2-coding-standard: ^3.4
- infection/infection: ^0.13.6
- mnapoli/pretty: ^1.0
- phpstan/phpstan: ^0.11
- phpunit/phpunit: ^8.1
- squizlabs/php_codesniffer: ^3.3
This package is auto-updated.
Last update: 2024-10-21 23:30:06 UTC
README
Why ?
In order to improve my skills, I'm doing my own implementation of a CommandBus.
Installation
composer require blacksmith-project/command-bus
How to set it up?
- Your handlers need to
- be callable (implements an
__invoke()
method). - be named after the command they handle:
$command = new AddSugarToCoffee(); $handler = new AddSugarToCoffeeHandler();
- be callable (implements an
- Handlers must be added to a
CommandHandlerMap
:$map = new SimpleCommandHandlerMap([$handler, $anotherHandler]); $map->add($yetAnotherHandler);
- Your
CommandBus
takes as parameter aCommandHandlerMap
.
How to do this in Symfony ?
- Declare your Handlers as a Service.
- Tag them with a specific tag such as
my_app.command_handler
. - Declare your
CommandHandlerMap
as a Service. - Make it use the tagged
my_app.command_handler
services as arguments. - Declare your
CommandBus
as a Service. - Make it use the
CommandHandlerMap
as argument.
Example:
# config/services.yaml ############ # Commands # ############ MyApp\Domain\ACommandHandler: tags: - 'my_app.command_handler' MyApp\Domain\AnothenCommandHandler: tags: - 'my_app.command_handler' ######################## # CommandHandlerMapper # ######################## BSP\CommandBus\SimpleCommandHandlerMap: arguments: [!tagged my_app.command_handler] ############## # CommandBus # ############## BSP\CommandBus\SimpleCommandBus: arguments: - BSP\CommandBus\SimpleCommandHandlerMap
How to use it?
Now, you only need to inject your CommandBus
and execute commands.
Example:
public function __construct(CommandBus $commandBus) { $this->commandBus = $commandBus; } public function doSomethingFromCLI(): void { $command = new DoSomething('please'); $this->commandBus->execute($command); $output->writeln('command has been executed.'); }