【发布时间】:2018-12-01 01:01:54
【问题描述】:
我有一个 DDD 项目,我不知道直接在订阅者中使用 Handler 或 Service 是否更好。
让我澄清一下;假设
- 命令对象必须只接收原始类型的输入
- 处理程序接收命令并转换域模型中的原始数据
我的问题是:如果我引发域事件,订阅者应该运行服务还是其他命令处理程序?
我举个例子:
class CommandOne{
public function __construct(string $stuff){
$this->stuff = $stuff;
}
public function getStuff(){
return $this->stuff;
}
}
// Handler, called from a ControllerAction
class HandlerCommandOne{
public function __construct(StuffRepository $stuffRepository,
SomeService $service){
$this->service = $service;
$this->stuffRepository = $stuffRepository;
}
public function handle(CommandOne $command){
$stuff = $command->getStuff();
$stuffModel = $this->stuffRepository->find($stuff);
//Some Business Logic
$this->service->doBusinessActivity();
$this->anotherService->doAnotherBusinessActivity();
// If I want that subscriber will use Service , I inject a model in event constructor
$this->dispatcher->dispatch(StuffEvent::NAME,new StuffEvent($stuffModel));
// If I want that subscriber will use a CommandHandler , I inject primitives in event constructor
$this->dispatcher->dispatch(StuffEvent::NAME,new StuffEvent($stuffModel->getId(),$stuffModel->getName()));
}
}
class SomeSubscriberWithHandler{
public function __construct(CommandHandler $handler) {
$this->handler = $handler;
}
public function OnStuffEvent($event){
$command = new SomeOtherCommand($event->getId(), $event->getName());
$this->handler->handle($command); // Handle will handle logic calling other services ...
}
}
class SomeSubscriberWithService{
public function __construct(Service $service) {
$this->service = $service;
}
public function OnStuffEvent($event){
$model = $event->getModel();
$this->service->doLogic($model);
}
}
我看到了利弊;我知道,在 DDD 中,最好使用 PRIMITIVES 数据创建事件,因为可以在有界上下文之外捕获事件,而您的模型可能没有意义。
但是如果我使用原语,每次我需要来自实体的信息时,我都必须调用存储库......
例如,订阅者必须通知新模型已创建,并发送电子邮件;你会在订阅者中创建处理程序,还是直接在服务中创建?
提前致谢
【问题讨论】:
标签: service domain-driven-design