流量: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 = [];
}
}
您不應該將您的聚合連接到特定的發佈者。更好的選擇是從事件存儲或存儲庫發佈記錄的事件。另外,您的DomainEventPublisher類不是線程安全的。你應該在那裏擁有線程本地成員,或者在PHP中有相同的東西。最後,它不是訂閱域事件的聚合。 AR發佈事件,他們不關心誰聽。您可以在其他任何地方添加訂閱者,在引導期間添加應用程序層,在特定的命令處理程序中添加基礎架構,如果某種方式有意義的話。 – plalx