Skip to content

Apply event state before persistence #200

Description

@aidan-casey

Description
Automatically apply event to aggregate upon recording to ensure state is accurately represented.

Example
In Greg Young's example of SimpleCQRS, you will note that the state is applied instantly to the aggregate the event is recorded on and the change tracked for persistence. It seems like this would make sense to replicate to simplify instances like the following:

final class Organization
{
    use WithEvents;
    use WithAggregateVersioning;

    #[Identifier]
    private OrganizationId $id;

    private string $name;

    public static function create(OrganizationId $organizationId, string $name): self
    {
        //
    }

    // This will fail because it is not defined upon persistence!
    public function getId(): OrganizationId
    {
        return $this->id;
    }

    public function getVersion(): int
    {
        return $this->version;
    }

    #[EventSourcingHandler]
    private function applyOrganizationWasCreated(OrganizationWasCreated $event): void
    {
        $this->id = new OrganizationId($event->organizationId);
        $this->name = $event->name;
    }
}

The only solution to this specific instance would be requiring the ID in the construct of the aggregate so it can be utilized during persistence.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions