andrewdevelop / command-bus
为 Lumen 设计的简单命令总线
2.0.0
2022-05-04 19:22 UTC
Requires
- php: ^8.0.2
- andrewdevelop/hex-contracts: ^2.0
- illuminate/container: ^9.0
- illuminate/support: ^9.0
This package is auto-updated.
Last update: 2024-09-04 13:58:43 UTC
README
这是一个适用于 Lumen 或 Laravel 6+ 的命令总线库。该包提供了在应用程序中执行可重用命令的基础设施:HTTP 控制器、CLI、队列等,同时也使您的代码更易于阅读和组织。服务通过简单的命名约定使用命令处理器执行所需的命令。
安装
该包可在 Packagist 上找到。要安装,只需运行
composer require andrewdevelop/command-bus
设置
只需将以下内容添加到您的 /bootstrap/app.php
文件中
$app->register(Core\Command\CommandBusServiceProvider::class);
用法
考虑在一个基本控制器中使用命令总线
<?php namespace App\Http\Controllers; use Laravel\Lumen\Routing\Controller; use Core\Contracts\CommandBus; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use App\Posts\Commands\CreatePostCommand; class PostController extends Controller { public function __construct(CommandBus $bus) { $this->bus = $bus; } public function store(Request $request) { $command = new CreatePostCommand($request->get('title'), $request->get('content')); $result = $this->bus->execute($command); if ($result) { return new JsonResponse($result, 201); } return new JsonResponse(['error' => 'Invalid request'], 400); } }
让我们创建一个基本的命令
<?php namespace App\Posts\Commands; use Core\Contracts\Command; class CreateAccountCommand implements Command { public $title; public $content; public function __construct(?string $title, ?string $content) { $this->title = $title; $this->content = $content; } }
让我们创建一个与命令关联的处理程序。命令处理器支持使用 Laravel 的服务容器进行构造函数依赖注入。
<?php namespace App\Posts\Handlers; class CreateAccountCommandHandler implements CommandHandler { protected $repository; public function __construct(Repository $repository) { $this->repository = $repository; } public function handle(Command $command) { $post = $this->repository->init(PostAggregateRoot::class); $post->create($command->title, $command->content); return $this->repository->save($post); } }
使用中间件
要全局注册额外的中间件,我们可以这样做
<?php // Somewhere in a service provider, or in /bootstrap/app.php $this->app->resolving(\Core\Contracts\CommandBus::class, function ($bus, $app) { $bus->middleware([ FixEmptyInputMiddleware::class, ValidateCommandMiddleware::class, // And a lot of things that are limited only by your imagination. ]); });
您的处理器必须实现 Core\Command\Middleware
接口,并返回一个 Core\Contracts\Command
的实例。中间件将在命令执行之前应用。
<?php use Core\Command\Middleware; use Core\Contracts\Command; class SomeMiddleware implements Middleware { public function handle(Command $command) { // Any code that can modify, validate, log or anything with the command. // And don't forget to return the command. return $command; } }