Snapshots
A snapshot is a cache of aggregate state at a particular event version. It
does not replace the event stream. On load, AggregateRepository applies the
snapshot and replays only events newer than the snapshot version.
Make an aggregate snapshotable
Implement SnapshotableAggregateInterface:
public function shouldTakeSnapshot(): bool;
public function getSnapshotClass(): string;
public function getSnapshotState(): array;
public function getSnapshotVersion(): EventVersion;
public function getAggregateId(): EntityIdentifierInterface;
public function applySnapshot(SnapshotInterface $snapshot): void;
The snapshot version must be the version represented by the returned state. The repository uses that version as the exclusive lower bound for tail replay.
Configure snapshot storage
The facade accepts snapshot storage, a snapshot factory, and optional snapshot history storage:
use DomainFlow\EventSourcing\Facade\EventSourcingFacade;
use DomainFlow\EventSourcing\Snapshot\GenericSnapshotFactory;
use DomainFlow\EventSourcing\Snapshot\InMemorySnapshotStorage;
use DomainFlow\EventSourcing\Storage\InMemoryEventStorage;
$facade = new EventSourcingFacade(
new InMemoryEventStorage(),
new InMemorySnapshotStorage(),
new GenericSnapshotFactory(),
);
GenericSnapshotFactory creates GenericSnapshot by default. A custom
snapshot class can use the constructor shape
(aggregateId, version, state, occurredOn); otherwise provide your own
SnapshotFactoryInterface.
When shouldTakeSnapshot() returns true, persist() generates and stores a
snapshot after storing the aggregate's uncommitted events. You can also call
createAndPersistSnapshot() explicitly. It returns null for a non-snapshotable
aggregate.
Snapshot history
SnapshotHistoryStorageInterface stores multiple versions per aggregate. It is
separate from SnapshotStorageInterface, which represents the current snapshot
used for loading. The history interface supports persisting a version,
retrieving all versions, deleting one version, and deleting all versions.
Deletion and fallback
EventSourcingFacade::delete() removes the aggregate's events and snapshot data
through the configured repository. If a snapshot cannot be trusted or does not
match the aggregate's declared type, the repository falls back to a full event
replay.