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

时间:2016-11-17 11:09:44

标签: php domain-driven-design domain-events

流程:

CreateNewTaskRequest - > CreateNewTaskService - > Task :: 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 = [];
    }
}

1 个答案:

答案 0 :(得分:1)

DomainEventPublisher类是单身,您可以使用

添加订阅者
DomainEventPublisher::instance()->subscribe(new YourSubscriber());

其中YourSubscriber实施DomainEventSubscriber