Database layer
Requires
- php: >=8.4
- ext-filter: *
- dibi/dibi: ^5.1
Requires (Dev)
- ext-mysqli: *
- ext-pdo: *
- codeception/codeception: ^5.3
- codeception/module-asserts: ^3.3
- codeception/module-db: ^3.2
- infection/codeception-adapter: ^0.4
- infection/infection: ^0.35
- rector/rector: ^2.9
- shipmonk/composer-dependency-analyser: ^1.8
- symplify/easy-coding-standard: ^13.3
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
A thin database abstraction layer on top of dibi for PHP 8.4+.
Provides base classes (Entity, Repository, Collection, QueryOptions) that consuming projects extend to build a typed, testable data-access layer with minimal boilerplate.
Changes between versions are listed in CHANGELOG.md.
Requirements
- PHP 8.4+ with
ext-filter - dibi/dibi ^5.1
Installation
composer require zdenekgebauer/db
Architecture
Entity
Base class for all domain objects. Extend it and add domain properties.
class Person extends Entity
{
public string $name = '';
public ?DateTimeImmutable $birthDate = null;
}
$id— primary key;0or negative means the record is new (not yet persisted)getId(): int/setId(int $id): void— accessors for$idisNew(): bool— returnstruewhen$id <= 0$deleted— set totruebyRepository::delete(); the library itself never reads it, it is a flag for the consuming project
Repository
Abstract generic base for data access. Extend it and implement getTableName(), find() and save(). The constructor takes a Dibi\IConnection; it must be a Dibi\Connection instance, otherwise InvalidArgumentException is thrown.
/** @extends Repository<Person> */
class PersonRepository extends Repository
{
protected function getTableName(): string
{
return 'persons';
}
public function find(PersonQueryOptions|QueryOptions $options): Collection
{
$fluent = $this->database->select('id, name, birth_date')
->from($this->getTableName())
->offset($options->getOffset())
->limit($options->limit);
if ($options->order !== '') {
$fluent->orderBy($options->order);
}
$this->setCriteria($fluent, $options);
$entities = [];
$result = $fluent->execute();
if ($result instanceof \Dibi\Result) {
foreach ($result as $row) {
$entity = new Person($row->id);
$entity->name = (string)$row->name;
$entity->birthDate = Helper::utcDate($row->birth_date);
$entities[] = $entity;
}
}
return new Collection($entities);
}
public function save(Person|Entity $entity): ActionResult
{
$result = new ActionResult();
$data = ['name' => $entity->name, 'birth_date' => $entity->birthDate];
try {
if ($entity->isNew()) {
$this->database->insert($this->getTableName(), $data)->execute();
$entity->id = $this->database->getInsertId();
} else {
$this->database->update($this->getTableName(), $data)
->where('%n = ?', $this->getPrimaryKey(), $entity->id)
->execute();
}
} catch (\Dibi\UniqueConstraintViolationException $e) {
$result->addError('Name already exists');
}
return $result;
}
}
Built-in methods (no implementation required):
| Method | Description |
|---|---|
findById(int $id): ?T | Returns single entity or null; skips DB call for $id <= 0 |
findByIds(int[] $ids): Collection<T> | Returns entities matching the given ids; ids without a record are skipped and the order is the database one, not the order of $ids; skips DB call for empty array |
findAll(int $max = 1000): Collection<T> | Returns up to $max entities |
findFirst(QueryOptions): ?T | Returns first match or null |
count(QueryOptions): int | COUNT(*) with criteria applied |
exists(QueryOptions): bool | Returns true when count > 0 |
delete(Entity): ActionResult | Deletes from DB, sets $entity->deleted = true, returns ActionResult (see below) |
getPrimaryKey(): string | Returns 'id'; override to change |
setCriteria() applies filterId and filterIds from QueryOptions automatically. Override it to add project-specific filters and call parent::setCriteria().
find() is declared @phpstan-impure: it reads the database, so PHPStan does not reuse the result of an earlier
call after the options changed. Implementations inherit the annotation.
Overriding delete()
The built-in delete() removes the row straight away and lets a Dibi\Exception propagate to the caller, so the ActionResult it returns is never a failure. Override it when the project needs to refuse a deletion or to report a database error as a message instead of an exception:
public function delete(Person|Entity $entity): ActionResult
{
$result = new ActionResult();
if ($entity->isSystemAccount()) {
$result->addError('Deletion is not allowed');
return $result;
}
try {
return parent::delete($entity);
} catch (\Dibi\ForeignKeyConstraintViolationException) {
$result->addError('Person is still referenced by an order');
return $result;
}
}
Note that parent::delete() sets $entity->deleted = true; when the override returns early with an error, the flag stays false.
Collection
Typed, iterable, countable wrapper around an array of entities.
$collection = $repository->findAll();
count($collection); // number of entities
$collection->isEmpty(); // true if empty
$collection->getFirst(); // first entity or null
$collection->getById(5); // find by id or null
$collection->getIds(); // array of all ids
$collection->entities(); // raw array
foreach ($collection as $entity) { ... }
QueryOptions
DTO passed to find(). Extend in consuming projects to add domain-specific filters.
class PersonQueryOptions extends QueryOptions
{
public string $filterName = '';
}
| Property / Method | Description |
|---|---|
int $limit | Constructor parameter; max rows to return (clamped to ≥ 1) |
int $page | Page number (clamped to ≥ 1); used with getOffset() |
string $order | Raw ORDER BY fragment |
int $filterId | Filter by primary key |
int[] $filterIds | Filter by set of primary keys (coerced to int[]) |
int $total | Total count (set by repository after count()) |
getOffset(): int | Calculates ($page - 1) * $limit |
getQueryStringParameters(): array | Override to expose filter state as URL parameters |
Criteria
Helper for building WHERE clauses. Use inside an overridden setCriteria().
protected function setCriteria(Fluent $fluent, QueryOptions $options): void
{
parent::setCriteria($fluent, $options);
if ($options instanceof PersonQueryOptions && $options->filterName !== '') {
new Criteria('name', Criteria::LIKE_ANY, $options->filterName)->apply($fluent);
}
}
| Operator constant | SQL produced |
|---|---|
Criteria::EQUALS | [col]=? |
Criteria::NOT_EQUALS | [col]<>? |
Criteria::IN | [col] IN (?) |
Criteria::NOT_IN | [col] NOT IN (?) |
Criteria::LIKE_ANY | [col] LIKE '%value%' |
Criteria::LIKE_START | [col] LIKE 'value%' |
Criteria::LIKE_END | [col] LIKE '%value' |
Criteria::IS_NULL | [col] IS NULL |
Criteria::IS_NOT_NULL | [col] IS NOT NULL |
Criteria::BETWEEN | [col] BETWEEN ? AND ? (value must be [min, max]) |
Criteria::CUSTOM | raw SQL fragment passed as $column |
Criteria::BETWEEN throws InvalidArgumentException when the value is not an array of at least two items,
Criteria::IN and Criteria::NOT_IN throw it when the value is not a non-empty array.
Order
Value object for ORDER BY fragments.
$options->order = new Order('name')->getOrderBy(); // [name] ASC
$options->order = new Order('created_at', Order::DESC)->getOrderBy(); // [created_at] DESC
$options->order = new Order('name ASC, age DESC', Order::CUSTOM)->getOrderBy(); // used as-is
An unknown direction falls back to Order::ASC.
ActionResult
Return type for save().
$result = $repository->save($entity);
if ($result->isFail()) {
echo $result->getMessageLine(); // comma-separated errors
}
addError(string $error)— append an error messageisFail(): bool— returnstruewhen errors are presentgetMessageLine(): string— all errors joined by,$errors— readable publicly; only settable within the class (protected(set))
Helper
Static utility methods.
Helper::boolFromSql($row->active); // float|int|string → bool
Helper::boolToSql($entity->active); // bool → 0|1
Helper::utcDate($row->created_at); // DateTimeInterface|string|bool|null → ?DateTimeImmutable (UTC)
Helper::isDuplicateKey($e, 'person_name_uq'); // UniqueConstraintViolationException for given key?
utcDate() returns null for an empty or unparsable value. It assumes the value is already in UTC (as stored in the
database) — the time is not converted between timezones, it is only labelled as UTC.
Development
Local environment runs on Lando (PHP 8.4 + xdebug):
lando install # install dependencies
lando tests # Unit + Integration suites
lando coverage # tests with code coverage report
lando dependency-analyser # composer.json dependencies against their usage in src/
lando infection # mutation testing (Infection), 100 % MSI required, report in build/reports/infection.txt
lando phpstan # static analysis (level max)
lando ecs # coding standards (PSR-12), lando ecs-fix to apply
lando rector # modernization dry-run, lando rector-fix to apply
Integration tests need the database service from .lando.yml and run with --env lando.
Infection runs them in a single thread, because Codeception repopulates the shared database before each test.
The Lando environment runs from WSL2 (~/projekty/Db); build/check-wsl.php stops it on Windows Lando or
a Windows drive.
License
MIT, see LICENSE.