trntv / yii2-command-bus
Yii2 Command Bus 扩展
3.2.0
2018-04-23 11:50 UTC
Requires
- yiisoft/yii2: ^2.0
- yiisoft/yii2-queue: ^2.0
Requires (Dev)
- phpunit/phpunit: ^4.8
- predis/predis: ^1.0
- symfony/process: ^3.0
- yiisoft/yii2-dev: ^2.0
Suggests
- symfony/process: ^3.0
- yiisoft/yii2-queue: ^2.0
README
为 Yii2 的 Command Bus
什么是 Command Bus?
Command Bus 的理念是创建代表应用要执行的操作的命令对象。然后,将其投入总线中,总线确保命令对象到达它需要去的地方。因此,命令进入 -> 总线将其交给处理者 -> 然后处理者实际完成工作。命令本质上代表了对服务层的调用。
安装
安装此扩展的首选方式是通过 composer。
运行以下命令之一
php composer.phar require --prefer-dist trntv/yii2-command-bus
或将其添加到您的 composer.json 文件中
"trntv/yii2-command-bus": "^1.0"
设置
1. 命令总线服务
安装后,第一步是设置命令总线组件。
return [ // ... 'components' => [ 'commandBus' => [ 'class' => 'trntv\bus\CommandBus' ] ], ];
2. 背景命令支持(可选)
安装所需的包
php composer.phar require symfony/process:^3.0
对于后台命令工作者,在您的配置中添加控制器和命令总线中间件
'controllerMap' => [ 'background-bus' => [ 'class' => 'trntv\bus\console\BackgroundBusController', ] ], 'components' => [ 'commandBus' =>[ ... 'middlewares' => [ [ 'class' => '\trntv\bus\middlewares\BackgroundCommandMiddleware', 'backgroundHandlerPath' => '@console/yii', 'backgroundHandlerRoute' => 'background-bus/handle', ] ] ... ] ],
创建后台命令
class ReportCommand extends Object implements BackgroundCommand, SelfHandlingCommand { use BackgroundCommandTrait; public $someImportantData; public function handle($command) { // do what you need } }
并异步运行它!
Yii::$app->commandBus->handle(new ReportCommand([ 'async' => true, 'someImportantData' => [ // data // ] ]))
3. 队列命令支持(可选)
3.1 安装所需的包
php composer.phar require yiisoft/yii2-queue
3.2 配置扩展
如果您需要命令在队列中运行,您需要设置中间件和 yii2-queue 扩展。
'components' => [ 'queue' => [ // queue config ], 'commandBus' =>[ ... 'middlewares' => [ [ 'class' => '\trntv\bus\middlewares\QueuedCommandMiddleware', // 'delay' => 3, // You can set default delay for all commands here ] ] ... ] ]
有关 yii2-queue 配置的更多信息,请参阅此处
3.4 运行队列工作者
yii queue/listen
更多信息 此处
3.5 创建并运行命令
class HeavyComputationsCommand extends Object implements QueuedCommand, SelfHandlingCommand { use QueuedCommandTrait; public function handle() { // do work here } } $command = new HeavyComputationsCommand(); Yii::$app->commandBus->handle($command)
4. 处理器
处理器是处理命令执行的对象。执行命令有两种可能的方式
4.1 外部处理器
return [ // ... 'components' => [ 'commandBus' => [ 'class' => 'trntv\bus\CommandBus', 'locator' => [ 'class' => 'trntv\bus\locators\ClassNameLocator', 'handlers' => [ 'app\commands\SomeCommand' => 'app\handlers\SomeHandler' ] ] ] ], ]; // or $handler = new SomeHandler; Yii::$app->commandBus->locator->addHandler($handler, 'app\commands\SomeCommand'); // or Yii::$app->commandBus->locator->addHandler('app\handlers\SomeHandler', 'app\commands\SomeCommand');
4.1 自处理命令
class SomeCommand implements SelfHandlingCommand { public function handle($command) { // do what you need } } $command = Yii::$app->commandBus->handle($command);