Projections with Document Store
PHP Event Sourcing Projections with Document Store
The Problem
What is the Document Store?
Building a Projection with Document Store
#[ProjectionV2('available_balance')]
#[FromAggregateStream(Account::class)]
class AvailableBalanceProjection
{
public function __construct(private DocumentStore $documentStore) {}
#[EventHandler]
public function whenAccountSetup(AccountSetup $event): void
{
$this->documentStore->addDocument(
'available_balance',
$event->accountId,
['balance' => 0]
);
}
#[EventHandler]
public function whenPaymentMade(PaymentMade $event): void
{
$current = $this->documentStore->getDocument(
'available_balance',
$event->accountId
);
$this->documentStore->updateDocument(
'available_balance',
$event->accountId,
['balance' => $current['balance'] + $event->amount]
);
}
#[QueryHandler('getCurrentBalance')]
public function getCurrentBalance(string $accountId): int
{
return $this->documentStore->getDocument(
'available_balance',
$accountId
)['balance'];
}
}Available Operations
Method
Description
Storing PHP Objects
Using upsertDocument for Simpler Logic
Lifecycle with Document Store
Testing with In-Memory Document Store
When to Use Document Store vs Raw SQL
Document Store
Raw SQL (Connection)
Last updated
Was this helpful?