【发布时间】:2016-09-06 03:30:57
【问题描述】:
我对域驱动的设计概念还很陌生,在使用带有命令和域逻辑命令处理程序的命令总线时,我遇到了在 API 中返回正确响应的问题。
假设我们正在使用领域驱动设计方法构建应用程序。我们有后端和前端部分。后端有我们所有的域逻辑和一个公开的 API。前端使用 API 向应用程序发出请求。
我们正在使用映射到命令总线的命令和命令处理程序来构建域逻辑。在我们的域目录下,我们有一个用于创建帖子资源的命令,称为 CreatePostCommand。它通过命令总线映射到其处理程序 CreatePostCommandHandler。
final class CreatePostCommand
{
private $title;
private $content;
public function __construct(string $title, string $content)
{
$this->title = $title;
$this->content= $content;
}
public function getTitle() : string
{
return $this->title;
}
public function getContent() : string
{
return $this->content;
}
}
final class CreatePostCommandHandler
{
private $postRepository;
public function __construct(PostRepository $postRepository)
{
$this->postRepository = $postRepository;
}
public function handle(Command $command)
{
$post = new Post($command->getTitle(), $command->getContent());
$this->postRepository->save($post);
}
}
在我们的 API 中,我们有一个用于创建帖子的端点。这是在我们的应用程序目录下的 PostController 中路由 createPost 方法。
final class PostController
{
private $commandBus;
public function __construct(CommandBus $commandBus)
{
$this->commandBus = $commandBus;
}
public function createPost($req, $resp)
{
$command = new CreatePostCommand($command->getTitle(), $command->getContent());
$this->commandBus->handle($command);
// How do we get the data of our newly created post to the response here?
return $resp;
}
}
现在在我们的 createPost 方法中,我们希望在响应对象中返回新创建的帖子的数据,以便我们的前端应用程序可以了解新创建的资源。 这很麻烦,因为我们知道根据定义命令总线不应该返回任何数据。所以现在我们陷入了一个令人困惑的境地,我们不知道如何将新帖子添加到响应中对象。
我不确定如何从这里开始处理这个问题,我想到了几个问题:
- 是否有一种优雅的方式可以在响应中返回帖子的数据?
- 我是否错误地实现了 Command/CommandHandler/CommandBus 模式?
- 这仅仅是 Command/CommandHandler/CommandBus 模式的错误用例吗?
【问题讨论】:
标签: php domain-driven-design api-design command-pattern