bowphp/cqrs

命令查询责任分离

1.2.1 2023-08-23 19:35 UTC

This package is auto-updated.

Last update: 2024-09-23 21:58:09 UTC


README

CQRS(命令查询责任分离)。这是我第一次听说由Greg Young描述的模式。其核心思想是,你可以使用与读取信息不同的模型来更新信息。在某些情况下,这种分离可能很有价值,但请注意,对于大多数系统来说,CQRS增加了风险复杂度。

更多信息

安装

该包需要php >= 8.1

composer require bowphp/cqrs

帮助

首先,创建示例命令

use Bow\CQRS\Command\CommandInterface;

class CreateUserCommand implements CommandInterface
{
    public function __construct(
        public string $username,
        public string $email
    ) {}
}

在这里创建处理程序

use Bow\CQRS\Command\CommandHandlerInterface;

class CreateUserCommandHandler implements CommandHandlerInterface
{
    public function __construct(public UserService $userService) {}

    public function process(CommandInterface $command): mixed
    {
        if ($this->userService->exists($command->email)) {
            throw new UserServiceException(
                "The user already exists"
            );
        }

        return $this->userService->create([
            "username" => $command->username,
            "email" => $command->email
        ]);
    }
}

将命令添加到 App\Configurations\ApplicationConfiguration::class 的注册中

use Bow\CQRS\Registration as CQRSRegistration;

public function run()
{
    CQRSRegistration::commands([
        CreateUserCommand::class => CreateUserCommandHandler::class
    ]);
}

在控制器中执行命令

namespace App\Controllers;

use App\Controllers\Controller;
use App\Commands\CreateUserCommand;

class UserController extends Controller
{
    public function __construct(private CommandBus $commandBus) {}

    public function __invoke(Request $request)
    {
        $payload = $request->only(['username', 'email']);
        $command = new CreateUserCommand(
            $payload['username'],
            $payload['email']
        );

        $result = $this->commandBus->execute($command);

        return redirect()
            ->back()
            ->withFlash("message", "User created");
    }
}

添加新路由

$app->post("/users/create", UserController::class);

贡献

感谢您考虑为Bow框架做出贡献!贡献指南在框架文档中。

联系

papac@bowphp.com - @papacdev

请,如果在项目中存在错误。通过电子邮件联系我,或在我的 slack 上留言。或者 加入我们