PHP code example of milpa / event-store

1. Go to this page and download the library: Download milpa/event-store 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/ */

    

milpa / event-store example snippets


use Milpa\EventStore\Event;
use Milpa\EventStore\FileEventStore;

$store = new FileEventStore('/var/data/orders.jsonl');

// Append: nextSeq() hands out the store-wide monotonic counter, one call per event.
$store->append(new Event('order-42', 'OrderPlaced', ['total' => 19.99], $store->nextSeq()));
$store->append(new Event('order-42', 'OrderShipped', ['carrier' => 'DHL'], $store->nextSeq()));

// Replay: every event for one stream, in ascending seq order — never other streams' events.
foreach ($store->replay('order-42') as $event) {
    printf("#%d %s %s\n", $event->seq, $event->type, json_encode($event->payload));
}
// #1 OrderPlaced {"total":19.99}
// #2 OrderShipped {"carrier":"DHL"}

$store->streams();  // ["order-42"]
$store->nextSeq();  // 3 — one past the highest seq in the store, across every stream

$state = array_reduce(
    $store->replay('order-42'),
    static fn (array $state, Event $event): array => match ($event->type) {
        'OrderPlaced' => [...$state, 'status' => 'placed', 'total' => $event->payload['total']],
        'OrderShipped' => [...$state, 'status' => 'shipped', 'carrier' => $event->payload['carrier']],
        default => $state,
    },
    [],
);
// ['status' => 'shipped', 'total' => 19.99, 'carrier' => 'DHL']