【问题标题】:DDD - Service or Handler in Subscriber?DDD - 订阅者中的服务或处理程序?
【发布时间】: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


    【解决方案1】:

    鉴于我们使用消息队列 (MQ) 实现有界上下文 (BC) 之间的通信,上游 BC 将通过将域事件转换为将发送到 MQ 的消息来发布它。

    另一方面,下游 BC 中的订阅者将是一个侦听器,将从 MQ 接收到的消息转换为命令,并运行命令处理程序。

    监听器是基础设施,因为它处理技术 (MQ)。它在应用程序之外,接受消息并调用应用程序服务(或命令处理程序)。

    这就是红皮书(实施领域驱动设计)示例中的做法。您可以通过https://github.com/VaughnVernon/IDDD_Samples查看他们

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-25
      • 1970-01-01
      • 1970-01-01
      • 2016-08-11
      相关资源
      最近更新 更多