Skip to the content
Precision Soft
All projects

Doctrine Utility

PHP

Reusable building blocks for Doctrine ORM. Repository base classes in a read-service style, query filters, join helpers and common entity traits.

View on GitHubcomposer require precision-soft/doctrine-utility

Doctrine Utility is a set of repository, DQL function and locking utilities for Doctrine ORM on MySQL, MariaDB and PostgreSQL. Its core is AbstractRepository. You inject it through the constructor, it acts as a read service, and it exposes only the query methods you implement, with reusable filters and join filters.

Around it sit typed criteria with keyset pagination and JSON and date DQL functions for the MySQL family. There is also a named-lock service for MySQL and PostgreSQL, a walker for MySQL index hints and two timestamp entity traits.

Installation

Requires PHP 8.2+, Doctrine ORM 3 and Doctrine DBAL 4. The DQL functions, MySqlWalker and MysqlLockService need MySQL or MariaDB and PostgresqlLockService needs PostgreSQL; the repositories and entity traits run on all three.

composer require precision-soft/doctrine-utility

Repositories as read services

Map the entity to DoctrineRepository, then write a repository that extends AbstractRepository and declares its entity class:

use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
use PrecisionSoft\Doctrine\Utility\Join\JoinCollection;
use PrecisionSoft\Doctrine\Utility\Repository\AbstractRepository;
 
class ProductRepository extends AbstractRepository
{
    public const JOIN_PRODUCT_TYPE = 'joinProductType';
 
    protected function getEntityClass(): string
    {
        return Product::class;
    }
 
    public function find(int $productId): Product
    {
        /** @var Product|null $product */
        $product = $this->getDoctrineRepository()->find($productId);
 
        if (null === $product) {
            throw new NotFoundException('the product was not found');
        }
 
        return $product;
    }
 
    protected function attachCustomFilters(QueryBuilder $queryBuilder, array $filters): JoinCollection
    {
        $joins = new JoinCollection();
 
        foreach ($filters as $key => $value) {
            switch ($key) {
                case static::JOIN_PRODUCT_TYPE:
                    $joins->addJoin(
                        new Join(
                            $value,
                            static::getAlias() . '.productType',
                            ProductTypeRepository::getAlias(),
                        ),
                    );
 
                    break;
                default:
                    throw new Exception(\sprintf('invalid filter `%s` for `%s::%s`', $key, static::class, __FUNCTION__));
            }
        }
 
        return $joins;
    }
}

Generic filter values bind through the column's Doctrine type, single or in a list, so a Uuid against a BINARY(16) column matches, and null maps to IS NULL. An empty array filter matches no rows by default; to make it an error instead, override getFlags() and return [EmptyArrayFilterBehavior::class => EmptyArrayFilterBehavior::ThrowException]. Override getLogger() to receive a warning when that fallback happens.

Typed criteria and keyset pagination

createQueryBuilderFromCriteria() is a typed alternative to the array filters, for queries built from validated input. Every field is checked against the mapping, so an unmapped name fails loudly instead of reaching DQL:

$criteria = new Criteria(
    filters: [
        new Filter('status', Operator::In, ['active', 'pending']),
        new Filter('deletedAt', Operator::IsNull),
    ],
    sorts: [
        new Sort('label', Direction::Ascending),
        new Sort('id', Direction::Ascending),
    ],
    limit: 20,
);
 
$queryBuilder = $this->createQueryBuilderFromCriteria($criteria);

Passing a Keyset with one value per sort field turns the sort list into a page boundary:

$nextPage = new Criteria(
    sorts: [new Sort('label'), new Sort('id')],
    keyset: new Keyset(['label' => $lastRow['label'], 'id' => $lastRow['id']]),
    limit: 20,
);

Sort on a combination that is unique overall, for example by appending the identifier. A keyset refuses null values and nullable sort columns, because rows holding NULL would be skipped and the engines order them differently.

DQL functions

JSON_CONTAINS, JSON_CONTAINS_PATH, JSON_EXTRACT, JSON_SEARCH, JSON_UNQUOTE and DATE_FORMAT, for MySQL and MariaDB:

doctrine:
    orm:
        dql:
            string_functions:
                JSON_CONTAINS: PrecisionSoft\Doctrine\Utility\Function\JsonContains
                JSON_EXTRACT: PrecisionSoft\Doctrine\Utility\Function\JsonExtract
                DATE_FORMAT: PrecisionSoft\Doctrine\Utility\Function\DateFormat

MySqlWalker adds USE, FORCE and IGNORE INDEX hints and SELECT ... FOR UPDATE to a DQL query through Query::setHint().

Named locks

LockServiceInterface is a portable named-lock contract, implemented by MysqlLockService (GET_LOCK() / RELEASE_LOCK()) and PostgresqlLockService (session-level advisory locks). Both are registered, so alias the interface to the one you want:

services:
    PrecisionSoft\Doctrine\Utility\Contract\LockServiceInterface:
        alias: PrecisionSoft\Doctrine\Utility\Service\PostgresqlLockService
$lockService->acquire('my-lock', timeout: 5);
 
if (true === $lockService->hasLockInCurrentSession('my-lock')) {
    /* this connection owns it, so the critical section is ours */
}
 
$lockService->release('my-lock');

Locks are reference-counted: each acquire() of the same name increments a counter and the lock is released on the server only when it reaches zero. acquire($name, forceRefresh: true) re-checks ownership with the engine, for connections that may have reconnected while holding the lock. hasLock() reports whether any session holds the lock; hasLockInCurrentSession() whether this one does.

Entity traits

CreatedTrait adds a created column and ModifiedTrait a modified column, both DATETIME defaulting to CURRENT_TIMESTAMP. ModifiedTrait updates itself through a #[ORM\PreUpdate] callback, so the entity must carry #[ORM\HasLifecycleCallbacks].

Documentation

  • README: the full reference, including the operator list, all DQL functions and walker hints, lock release semantics and exception context
  • Example application: a runnable product catalogue on MySQL, MariaDB and PostgreSQL
  • CHANGELOG