PHP code example of dbellettini / eventstore-client

1. Go to this page and download the library: Download dbellettini/eventstore-client 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/ */

    

dbellettini / eventstore-client example snippets


use KurrentDB\EventStore;
use KurrentDB\Http\GuzzleHttpClient;

// Create HTTP client and connect to KurrentDB
$httpClient = new GuzzleHttpClient();
$eventStore = new EventStore('http://admin:[email protected]:2113', $httpClient);

use KurrentDB\WritableEvent;
use KurrentDB\WritableEventCollection;

// Write a single event
$event = WritableEvent::newInstance(
    'UserRegistered',
    ['userId' => '123', 'email' => '[email protected]'],
    ['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);

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);

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');

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);

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);

// Filesystem cache
$httpClient = GuzzleHttpClient::withFilesystemCache('/tmp/kurrentdb-cache');

// APCu cache (in-memory)
$httpClient = GuzzleHttpClient::withApcuCache();

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

$eventStore = new EventStore($url, $httpClient);

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

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

use KurrentDB\Exception\StreamNotFoundException;
use KurrentDB\Exception\WrongExpectedVersionException;
use KurrentDB\Exception\StreamDeletedException;

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 (StreamDeletedException $e) {
    // Stream was deleted
    echo "Stream deleted: " . $e->getMessage();
}

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 = new EventStore($url, new MyCustomHttpClient());