rezzza / command-bus

简易命令总线

3.3.2 2017-06-29 07:59 UTC

This package is auto-updated.

Last update: 2024-09-08 06:50:23 UTC


README

Build Status

轻量级命令总线。

安装

composer.json:

    "rezzza/command-bus": "~2.0"

命令

命令必须实现一个接口 Rezzza\CommandBus\Domain\CommandInterface,它应该是一个值对象,例如

class ShortenUrlCommand
{
    private $longUrl;

    public function __construct($longUrl)
    {
        $this->longUrl = $longUrl;
    }

    public function getLongUrl()
    {
        return $this->longUrl;
    }
}

命令处理器

当命令总线处理命令时,将会调用命令处理器。

处理器可以是

- A callable (\Closure or a callback)
- An object. In example of ShortenUrlCommand, the bus will execute `$object->shortenUrl($command)`

命令总线

它将找到命令处理器然后处理命令。目前我们提供了三个命令总线

- Direct (synchronous)
- Redis (asynchronous)
- Rabbit (asynchronous)
- Implement your own command bus with `\Rezzza\CommandBus\Domain\CommandBusInterface`

您可以在 examples 目录中看到它们的作用。

失败策略

当总线处理命令,并且命令处理器失败时,您可能希望将命令重新入队以稍后执行。

- RetryThenFailStrategy: The command is requeued in a `Retry` queue, you'll be able to consume this queue and configure how many time you want to execute it before it goes to a `Fail` queue. Look at `examples/redis_worker.php` example to understand how it work.
- RequeueStrategy: The command is requeued
- NoneStrategy: The command will not being requeued.
- Your own strategy with `Rezzza\CommandBus\Domain\Consumer\FailStrategy\FailStrategyInterface`

消费者

在您的控制台命令中,您可以使用消费者来处理异步命令。例如,使用 redis,您将执行

do {
    $redis    = new \Redis();
    $redis->connect('......');

    $handlerLocator = new Rezzza\CommandBus\Infra\Handler\MemoryHandlerLocator();
    // add some handlers ...
    $directBus         = new Rezzza\CommandBus\Infra\Provider\Direct\DirectBus($handlerLocator);
    $failStrategy      = new Rezzza\CommandBus\Domain\Consumer\FailStrategy\NoneStrategy();
    $redisKeyGenerator = new CommandBus\Infra\Provider\Redis\RedisKeyGenerator();
    $serializer        = new CommandBus\Infra\Serializer\NativeSerializer();

    $consumer = new Rezzza\CommandBus\Domain\Consumer\Consumer(
        new Rezzza\CommandBus\Infra\Provider\Redis\RedisConsumerProvider($redis, $redisKeyGenerator, $serializer),
        $directBus,
        $failStrategy
    );

    $consumer->consume('FooCommand');
    sleep(1); // yep ...
} while (true);

示例是最好的文档,请查看 examples 目录。