tomaszhanc / cqrs-lite-write-model
0.2.1
2017-12-28 12:34 UTC
Requires
- php: >=7.1
Requires (Dev)
- phpunit/phpunit: ^6.0
This package is auto-updated.
Last update: 2024-08-29 04:48:25 UTC
README
有时你会遇到很多不同的命令,这些命令应该被视为一个命令来处理。一开始看起来很简单:创建一个命令并将其传递给 CommandBus
,然后创建另一个,再创建一个。但用户验证怎么办?我们希望在处理第一个命令之前对所有命令进行验证。如果我们通过 PATCH 请求来做,有时可能只需要处理一个命令,有时需要处理多个——这取决于请求。
处理多个命令... 或者只是处理一个
假设我们有一个针对 PATCH 请求的操作,并且我们有两个命令: Rename
和 Describe
。根据请求,我们希望创建这两个命令或者只创建一个
public function editAction(Request $request, $id) { $renameFactory = new CommandFactory('name'); $renameFactory->createBy(function (array $data) use ($id) { return new Rename($id, $data['name']); }); $describeFactory = new CommandFactory('description'); $describeFactory->createBy(function (array $data) use ($id) { return new Describe($id, $data['description']); }); $builder = new CommandsBuilder(); $builder->addCommandFactory($renameFactory); $builder->addCommandFactory($describeFactory); // $request->request->all() returns all data from the request (something like $_POST) $commands = $builder->createCommandsFor($request->request->all()); // here you can validate commands and then handle them via command bus foreach ($commands as $command) { $this->commandBus->handle($command); } }
方法 CommandsBuilder::createCommandsFor()
将只创建那些根据传入数据(例如,在 $request->request->all()
中的示例)中是否存在所需的字段(至少一个)应该创建的命令。上述示例可以通过使用 CommandsBuilderSupport
特性来简化。
use CommandsBuilderSupport; public function editAction(Request $request, $id) { $this->addCommandFor('name')->createBy( function (array $data) use ($id) { return new Rename($id, $data['name']); } ); $this->addCommandFor('description')->createBy( function (array $data) use ($id) { return new Describe($id, $data['description']); } ); $commands = $this->commandsBuilder->createCommandsFor($request->request->all()); foreach ($commands as $command) { $this->commandBus->handle($command); } }