2016-11-17 89 views
1

流量:PHP中的DDD - > DomainEventPublisher - >在哪里使用订阅方法?

CreateNewTaskRequest - > CreateNewTaskService - >任务:: writeFromNew() - > NewTaskWasCreated(域事件) - > DomainEventPublisher呼叫处理的用户。

按照上面的流程,我想知道你在哪些地方为域事件添加订阅者?

我目前正在阅读这本书DDD in PHP,但我无法掌握应该在哪里完成?

这是我的代码,但觉得我错了

public static function writeNewFrom($title) 
    { 
     $taskId = new TaskId(1); 
     $task = new static($taskId, new TaskTitle($title)); 

     DomainEventPublisher::instance()->subscribe(new MyEventSubscriber()); 

     $task->recordApplyAndPublishThat(
      new TaskWasCreated($taskId, new TaskTitle($title)) 
     ); 

     return $task; 
    } 

任务延长聚合根:

class AggregateRoot 
{ 
    private $recordedEvents = []; 

    protected function recordApplyAndPublishThat(DomainEvent $domainEvent) 
    { 
     $this->recordThat($domainEvent); 
     $this->applyThat($domainEvent); 
     $this->publishThat($domainEvent); 
    } 

    protected function recordThat(DomainEvent $domainEvent) 
    { 
     $this->recordedEvents[] = $domainEvent; 
    } 

    protected function applyThat(DomainEvent $domainEvent) 
    { 
     $modifier = 'apply' . $this->getClassName($domainEvent); 
     $this->$modifier($domainEvent); 
    } 

    protected function publishThat(DomainEvent $domainEvent) 
    { 
     DomainEventPublisher::instance()->publish($domainEvent); 
    } 

    private function getClassName($class) 
    { 
     $class = get_class($class); 
     $class = explode('\\', $class); 
     $class = end($class); 

     return $class; 
    } 

    public function recordedEvents() 
    { 
     return $this->recordedEvents; 
    } 

    public function clearEvents() 
    { 
     $this->recordedEvents = []; 
    } 
} 
+0

您不应该将您的聚合连接到特定的发布者。更好的选择是从事件存储或存储库发布记录的事件。另外,您的DomainEventPublisher类不是线程安全的。你应该在那里拥有线程本地成员,或者在PHP中有相同的东西。最后,它不是订阅域事件的聚合。 AR发布事件,他们不关心谁听。您可以在其他任何地方添加订阅者,在引导期间添加应用程序层,在特定的命令处理程序中添加基础架构,如果某种方式有意义的话。 – plalx

回答

1

DomainEventPublisher类是单,您可以用

添加一个用户
DomainEventPublisher::instance()->subscribe(new YourSubscriber()); 

其中YourSubscriber实施DomainEventSubscriber

+0

是的,但是什么时候应该在上面的流程中添加订户?你打哪个电话?在发布域事件之前的writeFromNew方法中? –

+0

你甚至在控制器被执行之前添加它。 – Federkun

+0

因此,例如,我的引导程序文件调用一个文件,其中添加了所有域事件的所有订阅者? –

相关问题