algsupport / yii2-command-bus
Yii2 命令总线扩展
v0.0.6
2022-07-01 18:48 UTC
README
Yii2 的命令总线
什么是命令总线?
命令总线的想法是创建代表您希望应用程序执行的操作的命令对象。然后,将其投入总线中,总线确保命令对象到达它需要去的地方。因此,命令进入 -> 总线将其交给处理者 -> 然后,处理者实际执行工作。命令本质上代表对您的服务层的方法调用。
安装
安装此扩展的首选方式是通过 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);