流れ:PHPのDDD - > DomainEventPublisher - > subscribeメソッドを使用する場所
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