聚合可以发出自己的命令吗?

时间:2019-08-08 09:51:58

标签: domain-driven-design cqrs event-sourcing aggregateroot

问题

AR 可以发出自己的命令,还是最好通过侦听外部命令发出的事件的处理器发出命令?

顺便说一句::如果您认为这个问题可能会导致“有主见”的答案,我仍然想知道它是否被认为是一种好的做法,以及为什么。

PHP代码示例

class PatchableComponent extends EventSourcedAggregateRoot
    implements Entity, ReconstitutableEventSourcedAggregateRoot
{
    ...

    public static function importFromCore(...): PatchableComponent
    {
        $patchableComponent = new self;

        $patchableComponent->applyPatchableComponentWasImportedFromCore(
            new PatchableComponentWasImportedFromCore(...)
        );

        // Here, the AR issue its own startLookingForPatches() command.
        $patchableComponent->startLookingForPatches();

        return $patchableComponent;
    }

    public function startLookingForPatches(): void
    {
        $this->applyPatchableComponentStartedLookingForPatches(
            new PatchableComponentStartedLookingForPatches(...)
        );
    }

    ...
}

2 个答案:

答案 0 :(得分:1)

  

AR可以发出自己的命令,还是最好通过侦听外部命令发出的事件的处理器发出命令?

聚合肯定可以调用其自己的方法;通常没有必要添加额外的间接层。

答案 1 :(得分:1)

我知道这个问题有一个可以接受的答案,但我想自己掏2美分。

当您声明聚合正在发出命令时,您的代码示例实际上并未执行该操作。您的示例是聚合执行特定行为的示例。 “命令”的概念是封装用户意图的消息(用例)的概念。 Command通常(并希望)由CommandHandler处理,然后该CommandHandler将调用Aggregate上的方法来执行工作。聚合并不真正了解用例。

如果将“命令”的概念与“聚合”的概念分开,则可以通过使域灵活的方式自由地实现“行为”。您可以彼此独立地添加新的用例(命令)和新的行为(在聚合中)。

相关问题