Skip to content
docsv0.2.4

FileRepository

File-JSON {@see RepositoryInterface}: the whole collection lives in one JSON file, keyed by id, read-modify-write on every mutation — the pattern the `example-agent-ready-blog`'s `JsonPostStorage` proved for a single entity, generalized here to any {@see EntityInterface}. Zero DB, zero dependency: a flat file is the entire durability story. A fresh `FileRepository` pointed at the same path — a different process, a different request — reads back exactly what the last write left, because every read and write goes through the file itself rather than an in-memory cache. Every mutation runs under an exclusive `flock` held across the whole read-modify-write cycle, and every read takes a shared lock — so concurrent processes over the same file can neither observe a torn write nor lose each other's rows.

FileRepository::__construct()

public function __construct(string $file, string $entityClass):

Parameters

Parameters of __construct()
NameTypeDescription
$filestringpath to the JSON collection file; its directory is created on first save if missing
$entityClassclass-string<T>the entity class rows are rehydrated into via `fromArray()`

FileRepository::find()

public function find(string|int $id): ?Milpa\Data\EntityInterface

The entity stored under `$id`, or `null` when no entity is stored under it.

Parameters

Parameters of find()
NameTypeDescription
$idstring|int

FileRepository::save()

public function save(Milpa\Data\EntityInterface $entity): string|int

Persists `$entity` to the file, under one exclusive lock held across the whole read-modify-write cycle — so a concurrent writer to the same file can neither steal the assigned id nor be overwritten. When `$entity->id()` is `null`, a fresh id is assigned via {@see self::nextId()}. The written row always carries the id actually used under the key `'id'`, regardless of what `$entity->toArray()` returned for it.

Parameters

Parameters of save()
NameTypeDescription
$entityT

FileRepository::delete()

public function delete(string|int $id): void

Removes the entity stored under `$id`, under the same exclusive read-modify-write lock as {@see self::save()}. A no-op when no entity is stored under it.

Parameters

Parameters of delete()
NameTypeDescription
$idstring|int

FileRepository::all()

public function all(): array

Every stored entity, in insertion order — rows live in the file in the order they were first saved, regardless of their ids.

FileRepository::nextId()

public function nextId(): int

The id to assign to the next entity saved without one of its own — one past the highest integer id currently in the file, or `1` when the file holds no integer id.

FileRepository::query()

public function query(array $criteria): array

Stored entities matching every `$criteria` pair by strict equality.

Parameters

Parameters of query()
NameTypeDescription
$criteriaarray<string, mixed>