PHP code example of solidframe / event-sourcing

1. Go to this page and download the library: Download solidframe/event-sourcing library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

solidframe / event-sourcing example snippets


use SolidFrame\EventSourcing\Aggregate\AbstractEventSourcedAggregateRoot;
use SolidFrame\Core\Event\DomainEventInterface;

final class BankAccount extends AbstractEventSourcedAggregateRoot
{
    private int $balance = 0;

    public static function open(AccountId $id, int $initialDeposit): self
    {
        $account = new self($id);
        $account->recordThat(new AccountOpened($id->value(), $initialDeposit));

        return $account;
    }

    public function deposit(int $amount): void
    {
        $this->recordThat(new MoneyDeposited($this->identity()->value(), $amount));
    }

    public function withdraw(int $amount): void
    {
        ($this->balance >= $amount) or throw InsufficientFunds::forAccount($this->identity()->value());

        $this->recordThat(new MoneyWithdrawn($this->identity()->value(), $amount));
    }

    // Event apply methods — called automatically during reconstitution
    protected function applyAccountOpened(AccountOpened $event): void
    {
        $this->balance = $event->initialDeposit;
    }

    protected function applyMoneyDeposited(MoneyDeposited $event): void
    {
        $this->balance += $event->amount;
    }

    protected function applyMoneyWithdrawn(MoneyWithdrawn $event): void
    {
        $this->balance -= $event->amount;
    }
}

use SolidFrame\EventSourcing\Repository\AggregateRootRepository;

$repository = new AggregateRootRepository(BankAccount::class, $eventStore);

// Save
$account = BankAccount::open(AccountId::generate(), 1000);
$account->deposit(500);
$repository->save($account);

// Load — replays all events to rebuild state
$account = $repository->load($accountId);

use SolidFrame\EventSourcing\Store\EventStoreInterface;

// Persist events with optimistic concurrency control
$eventStore->persist($aggregateId, expectedVersion: 0, events: [
    new AccountOpened($aggregateId->value(), 1000),
]);

// Load all events
$events = $eventStore->load($aggregateId);

// Load from a specific version
$events = $eventStore->loadFromVersion($aggregateId, fromVersion: 5);

use SolidFrame\EventSourcing\Exception\ConcurrencyException;

try {
    $eventStore->persist($aggregateId, expectedVersion: 3, events: $newEvents);
} catch (ConcurrencyException $e) {
    // Version conflict — reload and retry
}

use SolidFrame\EventSourcing\Store\InMemoryEventStore;

$eventStore = new InMemoryEventStore();

use SolidFrame\EventSourcing\Snapshot\SnapshotableAggregateRootInterface;

final class BankAccount extends AbstractEventSourcedAggregateRoot
    implements SnapshotableAggregateRootInterface
{
    private int $balance = 0;

    public function createSnapshotState(): mixed
    {
        return ['balance' => $this->balance];
    }

    public static function reconstituteFromSnapshot(
        IdentityInterface $id,
        int $version,
        mixed $state,
        iterable $remainingEvents,
    ): static {
        $account = new self($id);
        $account->balance = $state['balance'];
        $account->aggregateRootVersion = $version;

        foreach ($remainingEvents as $event) {
            $account->applyEvent($event);
        }

        return $account;
    }

    // ... rest of the aggregate
}

use SolidFrame\EventSourcing\Snapshot\SnapshotAggregateRootRepository;
use SolidFrame\EventSourcing\Snapshot\Snapshot;

$repository = new SnapshotAggregateRootRepository(
    BankAccount::class,
    $eventStore,
    $snapshotStore,
);

// Load: uses snapshot + remaining events (faster than full replay)
$account = $repository->load($accountId);

// Save a snapshot manually
$snapshotStore->save(new Snapshot(
    aggregateId: $accountId->value(),
    aggregateType: BankAccount::class,
    version: $account->aggregateRootVersion(),
    state: $account->createSnapshotState(),
));