Search by

Lightweight versioned key–value storage for PHP

Package info

github.com/rafalmasiarek/php-kv

pkg:composer/rafalmasiarek/php-kv

Statistics

Installs: 5

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 2

v1.0.0 2025-11-10 18:47 UTC

README

Tiny versioned key-value manager for PHP.

License

License: MIT

The MIT License (MIT)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files, to deal in the Software
without restriction.

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.

Source: https://opensource.org/licenses/MIT

See LICENSE for full details.

Authors

Concepts

Scope + ID + Key ⇒ versioned value.

Think of:

  • scope – logical bucket, e.g. "user", "feature", "tenant".
  • id – identifier inside scope, e.g. "123", "acme".
  • key – name inside that document, e.g. "theme", "feature_x_enabled".

Example:

use rafalmasiarek\KV;
use rafalmasiarek\KV\Storage\FileStorage;

$storage = new FileStorage(__DIR__ . '/storage');
$kv = new KV($storage);

// create versions
$kv->set('user', '123', 'theme', 'dark');
$kv->set('user', '123', 'theme', 'light');

// read latest
$current = $kv->get('user', '123', 'theme'); // "light"

// list all latest values for given (scope,id)
$all = $kv->all('user', '123');

// detailed info (with history)
$info = $kv->info('user', '123', 'theme');
// [
//   'schema'          => 'v1',
//   'current_version' => 2,
//   'created_at'      => '2025-01-01T12:00:00+00:00',
//   'updated_at'      => '2025-01-02T09:00:00+00:00',
//   'history'         => [
//       '1' => ['value' => 'dark',  'created_at' => '...'],
//       '2' => ['value' => 'light', 'created_at' => '...'],
//   ],
// ]

// delete a key (all its versions)
$kv->delete('user', '123', 'theme');

// delete whole document (scope+id)
$kv->deleteDocument('user', '123');

Installation

composer require rafalmasiarek/php-kv

Minimal usage

use rafalmasiarek\KV;
use rafalmasiarek\KV\Storage\FileStorage;

$kv = new KV(new FileStorage(__DIR__ . '/var/kv'));

// Set
$kv->set('app', 'flags', 'new_ui', true);

// Get
if ($kv->get('app', 'flags', 'new_ui')) {
    // ...
}

Schema format

Internally each (scope, id) document is stored as JSON:

{
  "schema": "v1",
  "keys": {
    "theme": {
      "schema": "v1",
      "current_version": 2,
      "created_at": "2025-01-01T12:00:00+00:00",
      "updated_at": "2025-01-02T09:00:00+00:00",
      "history": {
        "1": { "value": "dark",  "created_at": "2025-01-01T12:00:00+00:00" },
        "2": { "value": "light", "created_at": "2025-01-02T09:00:00+00:00" }
      }
    }
  }
}

Schemas are managed in one place: Schema\SchemaRegistry.

  • SchemaRegistry::CURRENT – currently used schema id (e.g. "v1").
  • SchemaRegistry::DEFINITIONS – associative array of all supported schema versions.
  • SchemaRegistry contains helpers used by KV for reading/updating documents and guarantees backwards compatibility: when you introduce "v2", old "v1" docs continue to work and can be upgraded or appended to.

To change schema:

  1. Add new entry in SchemaRegistry::DEFINITIONS.
  2. Update SchemaRegistry::CURRENT.
  3. Implement upgrade logic inside SchemaRegistry if shape changes.

Storage backends

All backends implement Storage\StorageInterface:

interface StorageInterface
{
    public function load(string $scope, string $id): ?array;
    public function save(string $scope, string $id, array $document): void;
    public function delete(string $scope, string $id): void;
}

Included:

  • FileStorage – JSON files on disk.
  • RedisStorage – single key per document (kv:{scope}:{id}).
  • MongoStorage – one document per (scope,id).

You can implement your own storage (e.g. SQL) by implementing this interface.

Index

Classes

Interfaces

KV

final class — rafalmasiarek\KV · source

KV Versioned key-value manager. Responsibilities: - Load/save documents via StorageInterface. - Maintain per-key version history using SchemaRegistry. - Provide simple API: set/get/all/info/history/delete/deleteDocument.

Depends on: StorageInterface

Method Visibility Returns Summary
__construct() public — —
set() public void Store a new value for (scope, id, key). Creates document if missing. Appends a new version when value changes.
get() public mixed Get latest value for (scope, id, key).
all() public array<string, mixed> Return all current values for a given (scope, id).
info() public array<string, mixed>|null Return detailed info for a single key (including history).
history() public array<string, array<string, mixed>> Get full history for given key.
delete() public void Delete single key (all its versions) from document.
deleteDocument() public void Delete whole document (scope + id).
now() private string Current RFC3339 timestamp in UTC.
__construct()

KV __construct()

source

public function __construct(StorageInterface $storage)
Param Type Description
$storage StorageInterface —
set()

KV set()

source

public function set(string $scope, string $id, string $key, mixed $value): void

Store a new value for (scope, id, key). Creates document if missing. Appends a new version when value changes.

Param Type Description
$scope string —
$id string —
$key string —
$value mixed —
get()

KV get()

source

public function get(string $scope, string $id, string $key, mixed $default): mixed

Get latest value for (scope, id, key).

Param Type Description
$scope string —
$id string —
$key string —
$default mixed —

Returns: mixed

all()

KV all()

source

public function all(string $scope, string $id): array

Return all current values for a given (scope, id).

Param Type Description
$scope string —
$id string —

Returns: array<string, mixed>

info()

KV info()

source

public function info(string $scope, string $id, string $key): ?array

Return detailed info for a single key (including history).

Param Type Description
$scope string —
$id string —
$key string —

Returns: array<string, mixed>\|null

history()

KV history()

source

public function history(string $scope, string $id, string $key): array

Get full history for given key.

Param Type Description
$scope string —
$id string —
$key string —

Returns: array<string, array<string, mixed>>

delete()

KV delete()

source

public function delete(string $scope, string $id, string $key): void

Delete single key (all its versions) from document.

Param Type Description
$scope string —
$id string —
$key string —
deleteDocument()

KV deleteDocument()

source

public function deleteDocument(string $scope, string $id): void

Delete whole document (scope + id).

Param Type Description
$scope string —
$id string —
now()

KV now()

source

private function now(): string

Current RFC3339 timestamp in UTC.

Returns: string

SchemaRegistry

final class — rafalmasiarek\Schema\SchemaRegistry · source

SchemaRegistry Central definition of document/key schemas for KV. All schema-specific decisions go through this class. Versioning rules: - Each stored document has top-level "schema". - Each key entry has its own "schema" so keys can migrate independently. - CURRENT defines which schema is used when creating new documents/keys. - When reading, unknown/missing schema falls back to CURRENT. This file is the only place you change when introducing e.g. v2.

Method Visibility Returns Summary
normalizeDocument() public static array<string, mixed> Normalize document to a known schema. - Ensures "schema" is set. - Ensures "keys" container exists. - Does NOT touch individual key payloads (handled lazily).
normalizeKey() public static array<string, mixed> Normalize a single key structure inside a document. - Ensures required fields exist. - Keeps history as-is if present.
normalizeDocument()

SchemaRegistry normalizeDocument()

source

public static function normalizeDocument(?array $doc): array

Normalize document to a known schema. - Ensures "schema" is set. - Ensures "keys" container exists. - Does NOT touch individual key payloads (handled lazily).

Param Type Description
$doc array<string, mixed>|null —

Returns: array<string, mixed>

normalizeKey()

SchemaRegistry normalizeKey()

source

public static function normalizeKey(?array $keyData, ?string $schemaId): array

Normalize a single key structure inside a document. - Ensures required fields exist. - Keeps history as-is if present.

Param Type Description
$keyData array<string, mixed>|null —
$schemaId string|null —

Returns: array<string, mixed>

FileStorage

final class — rafalmasiarek\Storage\FileStorage · source

FileStorage Simple JSON-file based storage: - One file per (scope, id). - File name: {scope}__{id}.json (both urlencoded for safety).

implements StorageInterface

Method Visibility Returns Summary
__construct() public — —
load() public ?array —
save() public void —
delete() public void —
path() private string —
__construct()

FileStorage __construct()

source

public function __construct(string $dir)
Param Type Description
$dir string —
load()

FileStorage load()

source

public function load(string $scope, string $id): ?array
Param Type Description
$scope string —
$id string —

Returns: ?array

save()

FileStorage save()

source

public function save(string $scope, string $id, array $document): void
Param Type Description
$scope string —
$id string —
$document array —
delete()

FileStorage delete()

source

public function delete(string $scope, string $id): void
Param Type Description
$scope string —
$id string —
path()

FileStorage path()

source

private function path(string $scope, string $id): string
Param Type Description
$scope string —
$id string —

Returns: string

MongoStorage

final class — rafalmasiarek\Storage\MongoStorage · source

MongoStorage Stores each (scope,id) as a single document: { _id: {scope}:{id}, scope, id, data: {...schema-managed...} }

implements StorageInterface

Depends on: Collection

Method Visibility Returns Summary
__construct() public — —
load() public ?array —
save() public void —
delete() public void —
id() private string —
__construct()

MongoStorage __construct()

source

public function __construct(Collection $collection)
Param Type Description
$collection Collection —
load()

MongoStorage load()

source

public function load(string $scope, string $id): ?array
Param Type Description
$scope string —
$id string —

Returns: ?array

save()

MongoStorage save()

source

public function save(string $scope, string $id, array $document): void
Param Type Description
$scope string —
$id string —
$document array —
delete()

MongoStorage delete()

source

public function delete(string $scope, string $id): void
Param Type Description
$scope string —
$id string —
id()

MongoStorage id()

source

private function id(string $scope, string $id): string
Param Type Description
$scope string —
$id string —

Returns: string

RedisStorage

final class — rafalmasiarek\Storage\RedisStorage · source

RedisStorage Stores each KV document as a single JSON string in Redis: key = prefix + scope + ':' + id

implements StorageInterface

Depends on: Redis

Method Visibility Returns Summary
__construct() public — —
load() public ?array —
save() public void —
delete() public void —
key() private string —
__construct()

RedisStorage __construct()

source

public function __construct(Redis $redis, string $prefix)
Param Type Description
$redis Redis —
$prefix string —
load()

RedisStorage load()

source

public function load(string $scope, string $id): ?array
Param Type Description
$scope string —
$id string —

Returns: ?array

save()

RedisStorage save()

source

public function save(string $scope, string $id, array $document): void
Param Type Description
$scope string —
$id string —
$document array —
delete()

RedisStorage delete()

source

public function delete(string $scope, string $id): void
Param Type Description
$scope string —
$id string —
key()

RedisStorage key()

source

private function key(string $scope, string $id): string
Param Type Description
$scope string —
$id string —

Returns: string

StorageInterface

interface — rafalmasiarek\Storage\StorageInterface · source

StorageInterface Minimal abstraction over a document store used by KV. Implementations are responsible for persistence only. Document shape is managed by SchemaRegistry and KV, not by storage.

Method Visibility Returns Summary
load() public array<string, mixed>|null Load document for given (scope, id). When no document exists, MUST return null.
save() public void Persist document for given (scope, id). Implementations MUST fully replace previous content.
delete() public void Delete document for given (scope, id). MUST NOT throw when document does not exist.
load()

StorageInterface load()

source

public function load(string $scope, string $id): ?array

Load document for given (scope, id). When no document exists, MUST return null.

Param Type Description
$scope string —
$id string —

Returns: array<string, mixed>\|null

save()

StorageInterface save()

source

public function save(string $scope, string $id, array $document): void

Persist document for given (scope, id). Implementations MUST fully replace previous content.

Param Type Description
$scope string —
$id string —
$document array<string, mixed> —
delete()

StorageInterface delete()

source

public function delete(string $scope, string $id): void

Delete document for given (scope, id). MUST NOT throw when document does not exist.

Param Type Description
$scope string —
$id string —