1

流量:

CreateNewTaskRequest -> CreateNewTaskService -> Task::writeFromNew() -> NewTaskWasCreated(domain event) -> 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 = [];
    }
}
4

1 回答 1

1

DomainEventPublisher类是一个单,你可以添加一个订阅者

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

在哪里YourSubscriber实现DomainEventSubscriber

于 2016-11-17T11:20:31.057 回答