PHPackages                             friendsofouro/kurrentdb-core - 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. friendsofouro/kurrentdb-core

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

friendsofouro/kurrentdb-core
============================

KurrentDB client for PHP (core)

v0.21.0(6mo ago)713624[1 issues](https://github.com/FriendsOfOuro/kurrentdb-php-core/issues)1MITPHPPHP ^8.4CI passing

Since May 20Pushed 1mo ago12 watchersCompare

[ Source](https://github.com/FriendsOfOuro/kurrentdb-php-core)[ Packagist](https://packagist.org/packages/friendsofouro/kurrentdb-core)[ RSS](/packages/friendsofouro-kurrentdb-core/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (20)Versions (34)Used By (1)

KurrentDB PHP Client
====================

[](#kurrentdb-php-client)

[![PHP 8](https://github.com/FriendsOfOuro/kurrentdb-php-core/actions/workflows/php_8.yml/badge.svg)](https://github.com/FriendsOfOuro/kurrentdb-php-core/actions/workflows/php_8.yml)[![Latest Stable Version](https://camo.githubusercontent.com/6ee9da3bbf28c55fc033d26469736add38aaeca341fd9e311ef82835dd8bc0e2/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f667269656e64736f666f75726f2f6b757272656e7464622d636f72652e737667)](https://packagist.org/packages/friendsofouro/kurrentdb-core)[![License](https://camo.githubusercontent.com/41f9bdc55d4e87ac10f85983577d88eb31e1ba5201f0803d0944150afd2363b6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f667269656e64736f666f75726f2f6b757272656e7464622d636f72652e737667)](https://packagist.org/packages/friendsofouro/kurrentdb-core)

A modern PHP client library for [KurrentDB](https://kurrent.io/) (formerly EventStoreDB) HTTP API, designed for event sourcing applications.

> **Note:** This library uses the HTTP API. For TCP integration, see [prooph/event-store-client](https://github.com/prooph/event-store-client).

Features
--------

[](#features)

- ✅ Support for KurrentDB HTTP API
- ✅ Event stream management (read, write, delete)
- ✅ Optimistic concurrency control
- ✅ Stream iteration (forward and backward)
- ✅ Batch operations for performance
- ✅ Built-in HTTP caching support
- ✅ PSR-7 and PSR-18 compliant
- ✅ Type-safe with PHP 8.4 features
- ✅ Comprehensive error handling

Architecture
------------

[](#architecture)

The library follows a clean architecture with a facade pattern that promotes separation of concerns and follows SOLID principles:

### Facade Pattern

[](#facade-pattern)

**EventStore** acts as a facade that delegates operations to specialized services:

- **StreamReader** - Handles all stream reading operations
- **StreamWriter** - Manages stream writing and deletion operations
- **StreamIteratorFactory** - Creates stream iterators for navigation

### Factory Pattern

[](#factory-pattern)

**EventStoreFactory** provides the recommended way to instantiate EventStore with proper dependency injection and connection validation:

```
// Simple creation with default dependencies
$eventStore = EventStoreFactory::create($uri);

// With custom HTTP client
$eventStore = EventStoreFactory::createWithHttpClient($uri, $httpClient);

// With all custom dependencies
$eventStore = EventStoreFactory::createWithDependencies(
    $uri,
    $httpClient,
    $streamReader,
    $streamWriter,
    $streamIteratorFactory
);
```

### Benefits

[](#benefits)

- **Testability** - Each service can be mocked independently
- **Separation of Concerns** - Clear boundaries between reading, writing, and iteration
- **SOLID Principles** - Interface segregation and dependency inversion
- **Maintainability** - Easier to extend and modify individual components
- **Type Safety** - Strong typing throughout the service layer

Requirements
------------

[](#requirements)

- PHP 8.4 or higher
- KurrentDB server (HTTP API enabled)

Installation
------------

[](#installation)

### Via Composer

[](#via-composer)

```
composer require friendsofouro/kurrentdb-core
```

### Via Metapackage (Recommended)

[](#via-metapackage-recommended)

For the complete package with additional integrations:

```
composer require friendsofouro/kurrentdb
```

### Local Development

[](#local-development)

```
git clone git@github.com:FriendsOfOuro/kurrentdb-php-core.git
cd kurrentdb-php-core

# Start the environment
make up

# Install dependencies
make install

# Run tests to verify setup
make test
```

Quick Start
-----------

[](#quick-start)

### Basic Setup

[](#basic-setup)

```
use KurrentDB\EventStoreFactory;

// Create EventStore using factory (recommended)
$eventStore = EventStoreFactory::create('http://admin:changeit@127.0.0.1:2113');

// Or with custom HTTP client
use KurrentDB\Http\GuzzleHttpClient;

$httpClient = new GuzzleHttpClient();
$eventStore = EventStoreFactory::createWithHttpClient(
    'http://admin:changeit@127.0.0.1:2113',
    $httpClient
);
```

### Writing Events

[](#writing-events)

```
use KurrentDB\WritableEvent;
use KurrentDB\WritableEventCollection;

// Write a single event
$event = WritableEvent::newInstance(
    'UserRegistered',
    ['userId' => '123', 'email' => 'user@example.com'],
    ['timestamp' => time()] // optional metadata
);

$version = $eventStore->writeToStream('user-123', $event);

// Write multiple events atomically
$events = new WritableEventCollection([
    WritableEvent::newInstance('OrderPlaced', ['orderId' => '456']),
    WritableEvent::newInstance('PaymentProcessed', ['amount' => 99.99])
]);

$eventStore->writeToStream('order-456', $events);
```

### Reading Events

[](#reading-events)

```
use KurrentDB\StreamFeed\EntryEmbedMode;

$feed = $eventStore->openStreamFeed('user-123');

// Get entries and read events
foreach ($feed->getEntries() as $entry) {
    $event = $eventStore->readEvent($entry->getEventUrl());
    echo sprintf("Event: %s, Version: %d\n",
        $event->getType(),
        $event->getVersion()
    );
}

// Read with embedded event data for better performance
$feed = $eventStore->openStreamFeed('user-123', EntryEmbedMode::BODY);
```

### Stream Navigation

[](#stream-navigation)

```
use KurrentDB\StreamFeed\LinkRelation;

// Navigate through pages
$feed = $eventStore->openStreamFeed('large-stream');
$nextPage = $eventStore->navigateStreamFeed($feed, LinkRelation::NEXT);

// Use iterators for convenient traversal
$iterator = $eventStore->forwardStreamFeedIterator('user-123');
foreach ($iterator as $entryWithEvent) {
    $event = $entryWithEvent->getEvent();
    // Process event...
}

// Backward iteration
$reverseIterator = $eventStore->backwardStreamFeedIterator('user-123');
```

### Optimistic Concurrency Control

[](#optimistic-concurrency-control)

```
use KurrentDB\ExpectedVersion;

// Write with expected version
$eventStore->writeToStream(
    'user-123',
    $event,
    5
);

// Special version expectations
$eventStore->writeToStream('new-stream', $event, ExpectedVersion::NO_STREAM);
$eventStore->writeToStream('any-stream', $event, ExpectedVersion::ANY);
```

### Stream Management

[](#stream-management)

```
use KurrentDB\StreamDeletion;

// Soft delete (can be recreated)
$eventStore->deleteStream('old-stream', StreamDeletion::SOFT);

// Hard delete (permanent, will be 410 Gone)
$eventStore->deleteStream('obsolete-stream', StreamDeletion::HARD);
```

Advanced Usage
--------------

[](#advanced-usage)

### HTTP Caching

[](#http-caching)

Improve performance with built-in caching:

```
// Filesystem cache
$httpClient = GuzzleHttpClient::withFilesystemCache('/tmp/kurrentdb-cache');
$eventStore = EventStoreFactory::createWithHttpClient($url, $httpClient);

// APCu cache (in-memory)
$httpClient = GuzzleHttpClient::withApcuCache();
$eventStore = EventStoreFactory::createWithHttpClient($url, $httpClient);

// Custom PSR-6 cache
use Symfony\Component\Cache\Adapter\RedisAdapter;
$cacheAdapter = new RedisAdapter($redisClient);
$httpClient = GuzzleHttpClient::withPsr6Cache($cacheAdapter);
$eventStore = EventStoreFactory::createWithHttpClient($url, $httpClient);
```

### Custom Service Dependencies

[](#custom-service-dependencies)

For advanced use cases, you can provide custom implementations of the core services:

```
use KurrentDB\EventStoreFactory;
use KurrentDB\Service\StreamReaderInterface;
use KurrentDB\Service\StreamWriterInterface;
use KurrentDB\Service\StreamIteratorFactoryInterface;

// Create custom service implementations
$customStreamReader = new MyCustomStreamReader($httpClient);
$customStreamWriter = new MyCustomStreamWriter($httpClient);
$customIteratorFactory = new MyCustomIteratorFactory($streamReader);

// Create EventStore with custom dependencies
$eventStore = EventStoreFactory::createWithDependencies(
    $uri,
    $httpClient,
    $customStreamReader,
    $customStreamWriter,
    $customIteratorFactory
);
```

### Batch Operations

[](#batch-operations)

Read multiple events efficiently:

```
// Collect event URLs
$eventUrls = [];
foreach ($feed->getEntries() as $entry) {
    $eventUrls[] = $entry->getEventUrl();
}

// Batch read
$events = $eventStore->readEventBatch($eventUrls);
foreach ($events as $event) {
    // Process events...
}
```

### Error Handling

[](#error-handling)

```
use KurrentDB\Exception\StreamNotFoundException;
use KurrentDB\Exception\WrongExpectedVersionException;
use KurrentDB\Exception\StreamGoneException;

try {
    $eventStore->writeToStream('user-123', $event, 10);
} catch (WrongExpectedVersionException $e) {
    // Handle version conflict
    echo "Version mismatch: " . $e->getMessage();
} catch (StreamNotFoundException $e) {
    // Stream doesn't exist
    echo "Stream not found: " . $e->getMessage();
} catch (StreamGoneException $e) {
    // Stream was permanently deleted (hard delete)
    echo "Stream gone: " . $e->getMessage();
}
```

### Custom HTTP Client

[](#custom-http-client)

You can provide your own HTTP client implementing `HttpClientInterface`:

```
use KurrentDB\Http\HttpClientInterface;

class MyCustomHttpClient implements HttpClientInterface
{
    public function send(RequestInterface $request): ResponseInterface
    {
        // Custom implementation
    }

    public function sendBatch(RequestInterface ...$requests): \Iterator
    {
        // Batch implementation
    }
}

$eventStore = EventStoreFactory::createWithHttpClient($url, new MyCustomHttpClient());
```

Development Setup
-----------------

[](#development-setup)

### Quick Start with Make

[](#quick-start-with-make)

```
# Start KurrentDB and build PHP container
make up

# Install dependencies
make install

# Run tests
make test

# Run tests with coverage
make test-coverage

# Check code style
make cs-fixer-ci

# Fix code style
make cs-fixer

# Run static analysis
make phpstan

# Run benchmarks
make benchmark

# View logs
make logs

# Stop containers
make down
```

Testing
-------

[](#testing)

The project uses PHPUnit for testing:

```
# Run all tests
make test

# Run with coverage report
make test-coverage

# Run specific test file
docker compose exec php bin/phpunit tests/Tests/EventStoreTest.php
```

API Reference
-------------

[](#api-reference)

### Main Classes

[](#main-classes)

- **`EventStore`** - Main facade class for all operations
- **`EventStoreFactory`** - Factory for creating EventStore instances with proper dependencies
- **`WritableEvent`** - Represents an event to be written
- **`WritableEventCollection`** - Collection of events for atomic writes
- **`StreamFeed`** - Paginated view of a stream
- **`Event`** - Represents a read event with version and metadata

### Service Classes

[](#service-classes)

- **`StreamReader`** - Handles stream reading operations
- **`StreamWriter`** - Manages stream writing and deletion
- **`StreamIteratorFactory`** - Creates stream iterators for navigation

### Enums

[](#enums)

- **`StreamDeletion`** - SOFT or HARD deletion modes
- **`EntryEmbedMode`** - NONE, RICH, or BODY embed modes
- **`LinkRelation`** - FIRST, LAST, NEXT, PREVIOUS, etc.

### Interfaces

[](#interfaces)

- **`EventStoreInterface`** - Main service interface
- **`HttpClientInterface`** - HTTP client abstraction
- **`WritableToStream`** - Objects that can be written to streams

Docker Environment
------------------

[](#docker-environment)

The project includes a complete Docker setup with:

- **KurrentDB** (latest) with projections enabled and health checks
- **PHP container** with all required extensions and dependencies
- Persistent volumes for KurrentDB data and logs
- Automatic service dependency management

The KurrentDB instance is configured with:

- HTTP API on port 2113
- Default credentials: `admin:changeit`
- All projections enabled
- AtomPub over HTTP enabled

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

Before submitting:

```
# Run tests
make test

# Check code style
make cs-fixer-ci

# Run static analysis
make phpstan

# Check source dependencies
make check-src-deps
```

### Dependency Validation

[](#dependency-validation)

The project includes dependency validation using `composer-require-checker` to ensure all used dependencies are properly declared in `composer.json`:

```
# Check for missing dependencies in source code
make check-src-deps
```

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

Disclaimer
----------

[](#disclaimer)

This project is not endorsed by Event Store LLP nor Kurrent Inc.

Support
-------

[](#support)

- [GitHub Issues](https://github.com/FriendsOfOuro/kurrentdb-php-core/issues)
- [Documentation](https://docs.kurrent.io/)
- [KurrentDB Community](https://kurrent.io/community)

###  Health Score

55

—

FairBetter than 98% of packages

Maintenance78

Regular maintenance activity

Popularity24

Limited adoption so far

Community27

Small or concentrated contributor base

Maturity82

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 90.9% of commits — single point of failure

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

Every ~139 days

Recently: every ~5 days

Total

31

Last Release

207d ago

PHP version history (5 changes)v0.1.0PHP &gt;5.4.0

v0.6.0PHP &gt;=5.5.0

v0.10.0PHP ~7.2

v0.13.0PHP ^8.3

v0.15.0PHP ^8.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/636b8faca454739517bb10dc0dc92bef04ca1f19babb122dbc88fbc1cb7dd51c?d=identicon)[dbellettini](/maintainers/dbellettini)

---

Top Contributors

[![dbellettini](https://avatars.githubusercontent.com/u/325358?v=4)](https://github.com/dbellettini "dbellettini (450 commits)")[![nicolopignatelli](https://avatars.githubusercontent.com/u/1071681?v=4)](https://github.com/nicolopignatelli "nicolopignatelli (19 commits)")[![fabiocarneiro](https://avatars.githubusercontent.com/u/1375034?v=4)](https://github.com/fabiocarneiro "fabiocarneiro (5 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (5 commits)")[![Akii](https://avatars.githubusercontent.com/u/1204017?v=4)](https://github.com/Akii "Akii (3 commits)")[![jclaveau](https://avatars.githubusercontent.com/u/1556489?v=4)](https://github.com/jclaveau "jclaveau (3 commits)")[![ohader](https://avatars.githubusercontent.com/u/402145?v=4)](https://github.com/ohader "ohader (3 commits)")[![cordoval](https://avatars.githubusercontent.com/u/328359?v=4)](https://github.com/cordoval "cordoval (2 commits)")[![fhoutr01](https://avatars.githubusercontent.com/u/28088908?v=4)](https://github.com/fhoutr01 "fhoutr01 (1 commits)")[![scrutinizer-auto-fixer](https://avatars.githubusercontent.com/u/6253494?v=4)](https://github.com/scrutinizer-auto-fixer "scrutinizer-auto-fixer (1 commits)")[![kmox83](https://avatars.githubusercontent.com/u/545491?v=4)](https://github.com/kmox83 "kmox83 (1 commits)")[![arnovr](https://avatars.githubusercontent.com/u/6443841?v=4)](https://github.com/arnovr "arnovr (1 commits)")[![codetriage-readme-bot](https://avatars.githubusercontent.com/u/35302948?v=4)](https://github.com/codetriage-readme-bot "codetriage-readme-bot (1 commits)")

---

Tags

EventSourcingEventStoreKurrentDB

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Rector

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/friendsofouro-kurrentdb-core/health.svg)

```
[![Health](https://phpackages.com/badges/friendsofouro-kurrentdb-core/health.svg)](https://phpackages.com/packages/friendsofouro-kurrentdb-core)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M648](/packages/sylius-sylius)[kreait/firebase-php

Firebase Admin SDK

2.4k39.7M72](/packages/kreait-firebase-php)[opensearch-project/opensearch-php

PHP Client for OpenSearch

15024.3M64](/packages/opensearch-project-opensearch-php)[shopware/platform

The Shopware e-commerce core

3.3k1.5M3](/packages/shopware-platform)[phpro/http-tools

HTTP tools for developing more consistent HTTP implementations.

28137.8k](/packages/phpro-http-tools)[getbrevo/brevo-php

Official Brevo provided RESTFul API V3 php library

963.1M35](/packages/getbrevo-brevo-php)

PHPackages © 2026

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