PHPackages                             twanhaverkamp/event-storage-in-mongodb-with-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. twanhaverkamp/event-storage-in-mongodb-with-php

ActiveLibrary[Database &amp; ORM](/categories/database)

twanhaverkamp/event-storage-in-mongodb-with-php
===============================================

Event Storage in MongoDB with PHP

1.0.0(4mo ago)00MITPHPPHP ^8.3CI passing

Since Jan 4Pushed 4mo agoCompare

[ Source](https://github.com/twanhaverkamp/event-storage-in-mongodb-with-php)[ Packagist](https://packagist.org/packages/twanhaverkamp/event-storage-in-mongodb-with-php)[ RSS](/packages/twanhaverkamp-event-storage-in-mongodb-with-php/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (5)Versions (2)Used By (0)

Event storage in MongoDB with PHP
=================================

[](#event-storage-in-mongodb-with-php)

This package is a [MongoDB](https://www.mongodb.com/) implementation for the ["Event Sourcing with PHP"](https://github.com/twanhaverkamp/event-sourcing-with-php) library.

**Table of Contents**

- [Usage](#usage)
    - [Installation](#installation)
    - [Implementation](#implementation)
        - [Connect with MongoDB](#connect-with-mongodb)
        - [Event storage](#event-storage)
    - [Dependency injection](#dependency-injection)
        - [Laravel project](#laravel-project)
        - [Symfony project](#symfony-project)

Usage
-----

[](#usage)

### Installation

[](#installation)

**Requirements:**

- PHP 8.3 (or higher)

If you're using [Composer](https://getcomposer.org/) in your project you can run the following command:

```
composer require composer require twanhaverkamp/event-storage-in-mongodb-with-php:^1.0
```

### Implementation

[](#implementation)

Most PHP frameworks like Symfony and Laravel allows you to register classes as services; If you like, you can register this Event store where you bind it to the EventStoreInterface.

#### Connect with MongoDB

[](#connect-with-mongodb)

When constructing the [Event Store](/src/Event/EventStore/MongoDb.php) you're required to pass an instance of the [MongoDB client](https://www.mongodb.com/docs/php-library/current/) as first argument, an Event describer instance as second argument and your [Database and Collection](https://www.mongodb.com/docs/php-library/current/databases-collections)names as third and fourth arguments.

```
// ...

use MongoDB\Client as MongoDbClient;
use TwanHaverkamp\EventSourcingWithPhp\Event\EventDescriber;
use TwanHaverkamp\EventStorageInMongoDbWithPhp\Event\EventStore;

// ...

$eventStore = new EventStore\MongoDb(
    new MongoDbClient(sprintf(
        'mongodb://%s:%s@%s:%d',
        'root',
        'password',
        'mongodb',
        27017,
    )),
    new EventDescriber\KebabCase(),
    'your-database-name',
    'your-collection-name',
);

// ...
```

> An Event describer can be found in the "Event Sourcing with PHP" library, which is automatically installed whenever you install this package. You can create your own Describer if you like; just make sure it implements the EventDescriberInterface, which can also be found in the "Event Sourcing with PHP" library.

#### Event registration

[](#event-registration)

In order for the Event Store to know which type of Events exist, you need to register them in the Event Store:

```
use TwanHaverkamp\EventSourcingWithPhp\Example;
use TwanHaverkamp\EventStorageInMongoDbWithPhp\Event\EventStore;

EventStore\MongoDb::register(
    Example\Event\InvoiceWasCreated::class,
    Example\Event\PaymentTransactionWasStarted::class,
    Example\Event\PaymentTransactionWasCompleted::class,
    Example\Event\PaymentTransactionWasCancelled::class,
);
```

> You have to register your Events before actually using the Event Store.

#### Event storage

[](#event-storage)

When you pass an Aggregate to the `save` function it loops over its Events and for every Event it will insert a new "document" for the constructed [Database and Collection](https://www.mongodb.com/docs/php-library/current/databases-collections) names.

### Dependency injection

[](#dependency-injection)

#### Laravel project

[](#laravel-project)

Create your own service provider when your working in a [Laravel](https://laravel.com) project to bind the MongoDB class to the EventStoreInterface:

```
namespace App\Providers;

use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use MongoDB\Client as MongoDbClient;
use TwanHaverkamp\EventSourcingWithPhp\Event\EventDescriber\KebabCase;
use TwanHaverkamp\EventSourcingWithPhp\Event\EventStore\EventStoreInterface;
use TwanHaverkamp\EventStorageInMongoDbWithPhp\Event\EventStore\MongoDb;

class EventStoreServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(EventStoreInterface::class, function (Application $app) {
            return new MongoDb(
                new MongoDbClient(sprintf(
                    'mongodb://%s:%s@%s:%d',
                    config('mongodb.username'),
                    config('mongodb.password'),
                    config('mongodb.host'),
                    config('mongodb.port'),
                )),
            new EventDescriber\KebabCase(),
            config('mongodb.database'),
            config('mongodb.collection'),
        });
    }
}
```

#### Symfony project

[](#symfony-project)

If you're working in a [Symfony](https://symfony.com/) project, you can leverage it's built-in "autowire" mechanism by registering the Event Store as a service in the `services.yaml`:

```
services:
  _defaults:
    bind:
      TwanHaverkamp\EventSourcingWithPhp\Event\EventDescriber\EventDescriberInterface: '@event.describer'
      TwanHaverkamp\EventSourcingWithPhp\Event\EventStore\EventStoreInterface: '@event_store.mongodb'

  # ...

  event.describer:
    class: TwanHaverkamp\EventSourcingWithPhp\Event\EventDescriber\KebabCase

  event_store.mongodb:
    class: TwanHaverkamp\EventStorageInMongoDbWithPhp\Event\EventStore\MongoDb
    arguments:
      $client: '@mongodb.client'
      $databaseName: '%env(string:MONGODB_DATABASE)%'
      $collectionName: '%env(string:MONGODB_COLLECTION)%'

  mongodb.client:
    class: MongoDB\Client
    arguments:
      $uri: '%env(string:MONGODB_URI)%'

  # ...
```

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance76

Regular maintenance activity

Popularity0

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

128d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/ef80a2db2114f61389f75e7729ccae77d666fdbb0754d09f3604662f9e01f519?d=identicon)[TwanHaverkamp](/maintainers/TwanHaverkamp)

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/twanhaverkamp-event-storage-in-mongodb-with-php/health.svg)

```
[![Health](https://phpackages.com/badges/twanhaverkamp-event-storage-in-mongodb-with-php/health.svg)](https://phpackages.com/packages/twanhaverkamp-event-storage-in-mongodb-with-php)
```

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k7.2M71](/packages/mongodb-laravel-mongodb)[doctrine/mongodb-odm

PHP Doctrine MongoDB Object Document Mapper (ODM) provides transparent persistence for PHP objects to MongoDB.

1.1k23.3M302](/packages/doctrine-mongodb-odm)[alcaeus/mongo-php-adapter

Adapter to provide ext-mongo interface on top of mongo-php-library

46412.3M73](/packages/alcaeus-mongo-php-adapter)[moloquent/moloquent

A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)

120114.6k7](/packages/moloquent-moloquent)[doesntmattr/mongodb-migrations

Managed Database Migrations for MongoDB

23598.7k1](/packages/doesntmattr-mongodb-migrations)[facile-it/mongodb-bundle

Bundle service integration of official \[mongodb/mongo-php-library\](https://github.com/mongodb/mongo-php-library) driver library

38212.1k1](/packages/facile-it-mongodb-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
