Skip to main content

Installation

Install with Composer

composer require domainflow/event-sourcing-mongodb

Connect the adapter

The adapter accepts a MongoDB\Database from the official PHP library:

use DomainFlow\EventSourcing\Facade\EventSourcingFacade;
use DomainFlow\EventSourcing\Snapshot\GenericSnapshotFactory;
use DomainFlow\EventSourcingMongoDB\Snapshot\MongoDbSnapshotStorage;
use DomainFlow\EventSourcingMongoDB\Storage\MongoDbEventStorage;
use MongoDB\Client;

$client = new Client('mongodb://127.0.0.1:27017/?replicaSet=rs0');
$database = $client->selectDatabase('my_app');

$facade = new EventSourcingFacade(
new MongoDbEventStorage($database),
new MongoDbSnapshotStorage($database),
new GenericSnapshotFactory(),
);

Snapshots are optional. The event storage alone is sufficient for full event replay.

Create indexes explicitly

Run schema setup as a deployment operation rather than relying on the first application write:

use DomainFlow\EventSourcingMongoDB\Schema\MongoDbSchemaManager;

$schema = new MongoDbSchemaManager($database);
$schema->ensureSchema();

The manager creates the adapter's required indexes. MongoDB collections are created as they are first written; the schema manager's important work is the indexes that make concurrency and timeout queries correct. dropSchema() deletes the adapter's collections and is intended for explicit environment teardown.

Replica set requirement

MongoDbEventStorage::storeEvents() uses one multi-document transaction for a whole call, including events for multiple aggregates. MongoDB transactions require a replica set or a sharded deployment. A single-node replica set is enough; a standalone mongod is not sufficient for the default behavior.

See MongoDB-specific configuration before using the adapter in production.