blacksmith-project / command-bus
一个PHP库
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-09-21 23:22:52 UTC
README
为什么?
为了提高我的技能,我正在实现自己的CommandBus。
安装
composer require blacksmith-project/command-bus
如何设置?
- 您的处理器需要
- 可调用的(实现了一个
__invoke()
方法)。 - 以它们处理的命令命名
$command = new AddSugarToCoffee(); $handler = new AddSugarToCoffeeHandler();
- 可调用的(实现了一个
- 处理器必须添加到
CommandHandlerMap
$map = new SimpleCommandHandlerMap([$handler, $anotherHandler]); $map->add($yetAnotherHandler);
- 您的
CommandBus
需要一个CommandHandlerMap
作为参数。
如何在Symfony中实现?
- 将处理器声明为服务。
- 用特定的标签标记它们,例如
my_app.command_handler
。 - 将
CommandHandlerMap
声明为服务。 - 使其使用标记的
my_app.command_handler
服务作为参数。 - 将
CommandBus
声明为服务。 - 使其使用
CommandHandlerMap
作为参数。
示例
# 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
如何使用它?
现在,您只需要注入您的CommandBus
并执行命令。
示例
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.'); }