blacksmith-project/command-bus

v0.5.0 2019-10-03 04:27 UTC

This package is auto-updated.

Last update: 2024-09-21 23:22:52 UTC


README

Scrutinizer Code Quality Code Coverage Build Status

为什么?

为了提高我的技能,我正在实现自己的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中实现?

  1. 将处理器声明为服务。
  2. 用特定的标签标记它们,例如my_app.command_handler
  3. CommandHandlerMap声明为服务。
  4. 使其使用标记的my_app.command_handler服务作为参数。
  5. CommandBus声明为服务。
  6. 使其使用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.');
}