chrisguitarguy/tactician-symfony-events

Symfony 事件分派器的 Tactician 中间件。

v2.0.0-RC1 2020-07-20 20:07 UTC

This package is auto-updated.

Last update: 2024-09-21 04:49:58 UTC


README

使用 Symfony 事件分派器 来接收命令接收、处理和/或在 Tactician 中的错误的通知。

用法

在任何地方添加中间件,在命令处理中间件之前。

use Symfony\Component\EventDispatcher\EventDispatcher;
use League\Tactician\CommandBus;
use Chrisguitarguy\Tactician\SymfonyEvents\EventMiddleware;
use Chrisguitarguy\Tactician\SymfonyEvents\CommandRecieved;
use Chrisguitarguy\Tactician\SymfonyEvents\CommandHandled;
use Chrisguitarguy\Tactician\SymfonyEvents\CommandFailed;

$eventMiddleware = new EventMiddlware($dispatcher = new EventDispatcher());

$commandBus = new CommandBus([
  // ...
  $eventMiddleware,
  $commandHandlerMiddleware,
  // ...
]);

您可以监听针对单个命令的特定事件。

use Acme\Example\SomeCommand;

$dispatcher->addListener('command.receieved.'.MyCommand::class, function (CommandReceived $event) {
    // called before the handler runs on SomeCommand
});

$dispatcher->addListener('command.handled.'.MyCommand::class, function (CommandHandled $event) {
    // called after the handler runs on SomeCommand
});

$dispatcher->addListener('command.failed.'.MyCommand::class, function (CommandFailed $event) {
    // called if one the handler or one of the `received` or `handled`
    // events throws an exeception from handling SomeCommand
});

$commandBus->execute(new SomeCommand());

或者监听在所有命令上触发的一般事件。

use Acme\Example\SomeCommand;

$dispatcher->addListener('command.receieved', function (CommandReceived $event) {
    // called before the handler runs on all commands
});

$dispatcher->addListener('command.handled', function (CommandHandled $event) {
    // called after the handler runs on all commands
});

$dispatcher->addListener('command.failed', function (CommandFailed $event) {
    // called if one the handler or one of the `received` or `handled`
    // events throws an exception from handling any command
});

$commandBus->execute(new SomeCommand());

还有一个 CommandEvents 类,它提供了一些常量和辅助函数来处理事件名称。

use Chrisguitarguy\Tactician\SymfonyEvents\CommandEvents;
use Acme\Example\SomeCommand;

// generic events are in constants.
$dispatcher->addListener(CommandEvents::RECEIVED, /*...*/);

// specific have helpers that take an object or class name
$dispatcher->addListener(CommandEvents::received(SomeCommand::class), /*...*/);

$command = new SomeCommand();
$dispatcher->addListener(CommandEvents::received($command), /*...*/);

$dispatcher->addListener(CommandEvents::HANDLED, /*...*/);
$dispatcher->addListener(CommandEvents::handled(SomeCommand::class), /*...*/);

$dispatcher->addListener(CommandEvents::FAILED, /*...*/);
$dispatcher->addListener(CommandEvents::failed(SomeCommand::class), /*...*/);

许可证

MIT。请参阅 LICENSE 文件。