Nexus API Reference

EventSourcedBehavior
in package

Read onlyYes
FinalYes

Fluent builder for event-sourced actor behaviors.

Event sourcing stores a sequence of domain events and rebuilds current state by replaying them. EventSourcedBehavior wires together a command handler (which produces Effects), an event handler (which folds events onto state), an EventStore, and optional snapshot/retention policies — then compiles everything into a Behavior via toBehavior().

On actor startup the PersistenceEngine loads the latest snapshot (if any), replays subsequent events, and only then delivers the first user command.

Example:

$behavior = EventSourcedBehavior::create(
    PersistenceId::of('Order', $orderId),
    new OrderState(),
    static fn (ActorContext $ctx, object $cmd, OrderState $state): Effect => match (true) {
        $cmd instanceof PlaceOrder => Effect::persist(new OrderPlaced($cmd->items)),
        $cmd instanceof CancelOrder => Effect::persist(new OrderCancelled()),
        default => Effect::none(),
    },
    static fn (OrderState $state, object $event): OrderState => match (true) {
        $event instanceof OrderPlaced    => $state->withItems($event->items),
        $event instanceof OrderCancelled => $state->cancel(),
        default => $state,
    },
)
    ->withEventStore($eventStore)
    ->withSnapshotStore($snapshotStore)
    ->withSnapshotStrategy(SnapshotStrategy::everyN(10))
    ->withRetention(RetentionPolicy::snapshotAndEvents(3, deleteEventsTo: true))
    ->toBehavior();
Tags
see
Effect

for the command-handler return type

PersistenceId

for actor identity

EventStore

for the event-stream storage contract

SnapshotStrategy

for snapshot frequency configuration

RetentionPolicy

for event pruning configuration

template

The state type

The event type

psalm-api

Table of Contents

Methods

create()  : self
Create a new EventSourcedBehavior builder.
toBehavior()  : Behavior
Build the final Behavior using PersistenceEngine.
withEventStore()  : self
Set the event store used to persist and replay domain events.
withReplayFilter()  : self
Set the replay filter applied when loading events on startup.
withRetention()  : self
Set the retention policy controlling how many snapshots and events are kept.
withSnapshotStore()  : self
Set an optional snapshot store for periodic state snapshots.
withSnapshotStrategy()  : self
Set the strategy that determines when snapshots are taken (e.g. every N events).
withWriterId()  : self
Override the writer ID used to stamp persisted envelopes.

Methods

create()

Create a new EventSourcedBehavior builder.

public static create(PersistenceId $persistenceId, object $emptyState, Closure $commandHandler, Closure $eventHandler) : self
Parameters
$persistenceId : PersistenceId

Unique identity for this persistent entity

$emptyState : object

Initial empty state before any events

$commandHandler : Closure

Processes commands, returns Effect

$eventHandler : Closure

Applies events to state (pure function)

Tags
psalm-suppress

UnusedParam Parameters are stored via constructor for later use

Return values
self

toBehavior()

Build the final Behavior using PersistenceEngine.

public toBehavior() : Behavior
Tags
throws
LogicException

if EventStore has not been set

psalm-suppress

MixedArgumentTypeCoercion Stored closures lose generic type info

Return values
Behavior

withReplayFilter()

Set the replay filter applied when loading events on startup.

public withReplayFilter(ReplayFilter $filter) : self

Use ReplayFilter::fail() (the default) to throw on writer conflicts, or one of the repair modes to handle multi-writer scenarios gracefully.

Parameters
$filter : ReplayFilter
Return values
self

withWriterId()

Override the writer ID used to stamp persisted envelopes.

public withWriterId(Ulid $writerId) : self

Defaults to a freshly generated ULID. Override when migrating data or running tests that need a deterministic writer identity.

Parameters
$writerId : Ulid
Return values
self
On this page

Search results