Search by

Doctrine-inspired ORM primitives for WordPress projects that keep wpdb as the database runtime.

Package info

github.com/SymPress/orm

pkg:composer/sympress/orm

Statistics

Installs: 1 642

Dependents: 1

Suggesters: 1

Stars: 1

Open Issues: 0

v1.0.0 2026-11-23 23:24 UTC

README

Checks Release PHP Downloads License: GPL-2.0-or-later

Status: Stable. 1.x follows Semantic Versioning as defined in docs/backward-compatibility.md; UPGRADE.md lists the changes needed to upgrade from 0.x.

Doctrine-inspired ORM primitives for WordPress projects that keep wpdb as the database runtime.

The package is intentionally not a full Doctrine ORM replacement. It brings the parts that are useful in a WordPress package architecture: attribute-based entity metadata, repositories, a Doctrine-like entity manager, deferred flush() writes, simple query building, schema SQL generation, and optional integration with sympress/migration.

WordPress remains the runtime. Existing plugins, core tables, $wpdb, and WordPress APIs continue to work normally.

Installation

composer require sympress/orm

When sympress/kernel is active, the package is discovered as a library bundle and registers its services and console commands automatically.

The root project should also require sympress/migration when ORM-managed schema migrations should be registered and executed through the migration bridge. The ORM requires Migration 1.0.8 or newer when that optional package is installed (older versions conflict); it provides lock ownership, typed operational errors and the explicit wp migration adopt --retire-superseded upgrade workflow.

Features

  • Attribute mapping with #[Entity], #[Table], #[Column], #[Index], #[UniqueConstraint], #[MappedSuperclass], embeddables, and PHP enums
  • Identifier mapping with #[Id]
  • Generated identifiers with #[GeneratedValue]
  • Cache mapping with #[Cache] on entities and associations
  • To-one and to-many association mapping with simple or composite join columns and join tables
  • Lazy to-many collections and lazy to-one references (native PHP lazy objects)
  • Single-table inheritance; queries on a subclass see only the rows of that class and its mapped subclasses
  • Cascade persist/remove and owning many-to-many join-table synchronization
  • Lifecycle callbacks and event listeners for common ORM lifecycle events
  • Entity metadata discovery from active SymPress kernel bundles
  • Optional metadata cache
  • Doctrine-like EntityManager, with EntityManagerInterface and RepositoryInterface for consumers, decorators and test doubles
  • Deferred persistence with persist() and flush(); persist() of an object whose row exists writes what differs from the row
  • UnitOfWork with managed entities, original data snapshots, identity map, entity states, scheduled insertions, scheduled deletions, and change detection
  • CRUD-oriented Repository
  • find(), findAll(), findBy(), findOneBy(), and matching() with Criteria
  • Explicit remove(), detach(), clear(), close(), refresh(), and contains()
  • Lazy entity references with getReference() that load on first access
  • Transaction helper with transactional()
  • Automatic transaction wrapping during flush()
  • Version columns, optimistic lock checks, and pessimistic lock helpers
  • Deferred implicit and deferred explicit change tracking
  • Hydration and extraction for string, integer, float, decimal, boolean, date, datetime, time, JSON, array and enum column values
  • Query builder with entity-field-to-column translation, joins, join conditions, grouping, ordering, limits, offsets, object parameters, and array parameters; fragments that would change the statement are rejected
  • DQL-style SELECT, UPDATE, and DELETE queries with mapped fields, joins, named parameters, positional parameters, expanded array parameters, custom DQL functions, and output walkers
  • Criteria objects, scalar/array result helpers, iterable results, and optional query result caching
  • Optional second-level entity and association cache with simple cache regions. Region versions live in the PHP process, so only request-scoped caches such as the bundled ArrayCache are supported; a persistent cache would keep entries that a region eviction in an earlier request invalidated
  • Schema SQL generation for WordPress-friendly CREATE TABLE statements
  • Live schema update SQL for missing and changed columns/indexes, opt-in destructive drops, and missing join tables, including single-table inheritance table deduplication
  • dbDelta() compatibility through generated CREATE TABLE SQL
  • Mapping validation for identifiers, associations, join metadata, and inheritance discriminator metadata
  • Optional migration bridge for sympress/migration
  • Console commands for mapping inspection, schema SQL, and migration class generation

Entity Mapping

<?php

declare(strict_types=1);

namespace App\Mailer\Entity;

use App\Mailer\Repository\EmailLogRepository;
use SymPress\Orm\Mapping\Column;
use SymPress\Orm\Mapping\Entity;
use SymPress\Orm\Mapping\Id;
use SymPress\Orm\Mapping\Index;

#[Entity(table: 'sympress_mailer_logs', repositoryClass: EmailLogRepository::class)]
#[Index(name: 'status_created', columns: ['status', 'createdAt'])]
final class EmailLog
{
    public function __construct(
        #[Id]
        #[Column(type: 'string', length: 32)]
        public string $id,

        #[Column(type: 'datetime')]
        public \DateTimeImmutable $createdAt,

        #[Column(type: 'string', length: 20)]
        public string $status,

        #[Column(type: 'json', nullable: true)]
        public array $payload = [],
    ) {
    }
}

Table names are stored without the WordPress prefix. The ORM adds $wpdb->prefix at runtime, so sympress_mailer_logs becomes wp_sympress_mailer_logs on a default install.

If table is omitted, the table name is derived from the short class name: EmailLog becomes email_log.

If a #[Column] name is omitted, the property name is converted to snake case: createdAt becomes created_at.

Supported Column Types

The column type catalog is frozen for 1.x. The schema generator maps each mapping type to a MySQL column type for WordPress tables, and the hydrator converts the strings wpdb returns:

Mapping type MySQL column PHP type on read Written as
string, varchar varchar(length), length 255 by default string the value
guid, uuid varchar(36) string the value
text, mediumtext, longtext the same name string the value
json, array, simple_array longtext array json_encode() with unescaped slashes
smallint, integer, int, bigint smallint, int, bigint; unsigned: true adds unsigned int the value
boolean, bool tinyint(1) bool 1 or 0
float, double float, double float the value
decimal decimal(precision,scale), decimal(10,0) by default float the value
date, date_immutable date \DateTime, \DateTimeImmutable Y-m-d
datetime, datetime_immutable datetime \DateTime, \DateTimeImmutable Y-m-d H:i:s
time, time_immutable time \DateTime, \DateTimeImmutable on 1970-01-01 H:i:s
  • decimal hydrates as float, so its precision is that of a PHP float. Store exact amounts, such as money, as integers or strings.
  • json, array and simple_array are stored as JSON and always hydrate to a PHP array. A JSON scalar or invalid JSON reads as []. simple_array is not Doctrine's comma-separated format.
  • time values carry the date 1970-01-01, so the same row always yields an equal value.
  • Date and time values are written in the timezone of the object and read in PHP's default timezone; the ORM does not convert timezones.
  • A column with enumType reads through BackedEnum::from() and writes the enum's backing value.
  • null reads and writes SQL NULL for every type.

Other plain MySQL type names, such as char(2) or tinyint unsigned, are passed through unchanged and read as the string wpdb returns. Anything else is rejected.

Table, column, index and join column names must be plain SQL identifiers (letters, digits and underscores, not starting with a digit). Generated DDL quotes them with backticks.

Entity Manager

The entity manager follows the normal Doctrine workflow: persist() schedules work, and flush() writes the changes.

use App\Mailer\Entity\EmailLog;
use SymPress\Orm\EntityManagerInterface;

final readonly class MailerService
{
    public function __construct(private EntityManagerInterface $entities)
    {
    }

    public function logQueuedMail(string $id, array $payload): void
    {
        $log = new EmailLog(
            $id,
            new \DateTimeImmutable(),
            'queued',
            $payload,
        );

        $this->entities->persist($log);
        $this->entities->flush();
    }
}

Calling persist() does not immediately call $wpdb->insert() or $wpdb->update(). The entity is registered in the UnitOfWork. The SQL write happens during flush().

persist() on an object that is not managed yet reads the row of its identifier (one SELECT). Without a row the object is new and inserted. With a row, the row becomes the object's original data and flush() writes what differs between the object and the row, also under explicit change tracking: persist(new Setting('site', 'new value')) updates the existing row, and an object equal to its row writes nothing. To-one foreign keys take part; an owning many-to-many collection that is not empty replaces the join rows, as for any newly attached object. A version column must carry the row's current version, or flush() throws OptimisticLockException. A row that belongs to another class of the inheritance hierarchy makes persist() throw a LogicException. prePersist does not run for an existing row, and a mapped property the object never initialized is not a value: it takes the row's value instead of writing NULL. persist() throws a LogicException when another instance with the same identifier is already managed, including an unloaded reference that a loaded association points at; find() the entity and change it instead. A persist() that throws leaves nothing scheduled.

Type-hint EntityManagerInterface in application code; the container aliases it to the EntityManager service, and decorators and test doubles can implement it. It holds the application API; methods that only the ORM's own classes call, such as table name and identifier helpers, stay on EntityManager. Its getRepository() returns a RepositoryInterface with the read methods find(), findAll(), findBy(), findOneBy() and matching(); save(), remove() and createQueryBuilder() stay on the Repository base class, which EntityManager::getRepository() still returns.

Change Tracking

Managed entities are snapshotted when they are persisted, inserted, or hydrated from a query. Later changes are detected during flush().

$log = $entityManager->find(EmailLog::class, 'log_123');

if ($log === null) {
    return;
}

$log->status = 'sent';

$entityManager->flush();

Only changed columns are sent to $wpdb->update(). Identifier columns are not updated.

Removing Entities

$log = $entityManager->find(EmailLog::class, 'log_123');

if ($log !== null) {
    $entityManager->remove($log);
    $entityManager->flush();
}

remove() schedules a deletion. The row is deleted during flush(). An unloaded reference from getReference() is loaded first, so cascades and orphan removal reach its associations; a missing row throws EntityNotFoundException; a cascaded remove skips an associated reference whose row is already gone. Use DQL DELETE to delete without loading.

If a new entity is persisted and then removed before the next flush, the pending insertion is cancelled.

Identity Map

The UnitOfWork keeps an identity map for managed entities. Repeated find() calls for the same entity class and identifier return the already managed object when possible.

$first = $entityManager->find(EmailLog::class, 'log_123');
$second = $entityManager->find(EmailLog::class, 'log_123');

assert($first === $second);

Use detach() to stop tracking one entity or clear() to reset all managed state.

$entityManager->detach($log);
$entityManager->clear();

getReference() and to-one associations return a native PHP lazy object that holds only the identifier. Reading the identifier does not query; the first access to any other property loads the row. A missing row throws EntityNotFoundException. Each reference costs one query, so looping over $article->author->name issues one query per author (N+1); join the association or load the authors with one query first, and the references are filled from those rows.

Repositories

Every entity can use the base Repository, or a custom repository can be set on the entity attribute.

<?php

declare(strict_types=1);

namespace App\Mailer\Repository;

use App\Mailer\Entity\EmailLog;
use SymPress\Orm\Repository;

final class EmailLogRepository extends Repository
{
    /** @return list<EmailLog> */
    public function queued(int $limit = 50): array
    {
        return $this->findBy(
            ['status' => 'queued'],
            ['createdAt' => 'ASC'],
            $limit,
        );
    }
}

Resolve repositories through the entity manager:

$logs = $entityManager->getRepository(EmailLog::class);

$one = $logs->find('log_123');
$all = $logs->findAll();
$queued = $logs->findBy(['status' => 'queued']);
$latest = $logs->findOneBy(['status' => 'sent']);

$logs->save($log);
$logs->remove($log);
$entityManager->flush();

The repository helpers accept an optional $flush argument for common small workflows:

$logs->save($log, flush: true);
$logs->remove($log, flush: true);

save() is persist(): it inserts a new object and writes the state of an object whose row already exists.

Query Builder

The query builder accepts entity fields and compiles them to prefixed table and column names.

$query = $entityManager
    ->createQueryBuilder()
    ->select('l')
    ->from(EmailLog::class, 'l')
    ->where('l.status = :status')
    ->setParameter('status', 'queued')
    ->orderBy('l.createdAt', 'ASC')
    ->setMaxResults(50)
    ->getQuery();

$logs = $query->getResult();

The generated SQL still goes through $wpdb->prepare(). Write a literal % as is, for example LIKE 'que%'; the builder escapes it for prepare(). Parameters work in select() expressions too.

select(), where(), having(), groupBy(), join conditions, Criteria expressions and DQL strings are SQL expression fragments. Mapped field paths and :name or ?1 parameters are rewritten in them; quoted literals ('...', "...", `...`) are left exactly as written. A ;, a subselect (SELECT, TABLE), UNION, INTERSECT, EXCEPT, a comment (/*, #, -- ), an unterminated literal or unbalanced parentheses outside a literal throws InvalidArgumentException.

Keep dynamic values out of query strings. The builder validates mapped field paths and prepares parameter values, but it cannot make interpolated strings safe. Put request data in setParameter() or setParameters() instead of concatenating it into where(), andWhere(), orWhere(), having(), andHaving(), join() conditions, or DQL strings. orderBy() only accepts mapped field paths; choose from an allow-list before passing user-controlled sort fields.

Supported query builder features:

  • select()
  • from()
  • join()
  • innerJoin()
  • leftJoin()
  • where()
  • andWhere()
  • orWhere()
  • groupBy()
  • addGroupBy()
  • having()
  • andHaving()
  • orderBy()
  • addOrderBy()
  • setParameter()
  • setParameters()
  • setMaxResults()
  • setFirstResult()
  • getQuery()
  • getSQL()

DQL-Style Queries

The ORM includes a pragmatic DQL-style subset for reads and bulk writes:

$query = $entityManager->createQuery(
    'SELECT l FROM EmailLog l WHERE l.status = :status ORDER BY l.createdAt DESC',
    ['status' => 'queued'],
);

$logs = $query->getResult();

Supported DQL subset:

  • one root entity
  • one alias
  • SELECT alias, or a list of mapped fields and expressions such as function calls
  • JOIN, INNER JOIN, and LEFT JOIN over mapped to-one, one-to-many, and many-to-many associations, with an optional WITH condition
  • WHERE expressions using mapped fields
  • named parameters and positional parameters
  • GROUP BY and HAVING
  • ORDER BY one or more mapped fields
  • bulk UPDATE
  • bulk DELETE

Bulk DQL queries can be executed through execute():

$entityManager
    ->createQuery(
        'UPDATE EmailLog l SET l.status = :status WHERE l.id = ?1',
        ['status' => 'sent', 1 => 'log_123'],
    )
    ->execute();

A SELECT that contains anything else, such as JOIN ... ON, LIMIT, a second FROM entity, or a misspelled keyword, throws InvalidArgumentException instead of being compiled without that part. Use setMaxResults() on the query builder for limits.

Clauses are split outside string literals, so WHERE l.status = 'x ORDER BY y' compares with that string. The fragment rules of the query builder apply.

This is not a full Doctrine DQL parser. Subqueries, partial object hydration, full AST walkers, and the complete Doctrine grammar are not part of this package. Lightweight custom DQL functions and SQL output walkers can be registered on the entity manager.

Transactions

Use transactional() for unit-of-work style transactions.

$entityManager->transactional(function (EntityManager $entities) use ($log): void {
    $entities->persist($log);

    $log->status = 'sent';
});

The callback is wrapped in:

  • START TRANSACTION
  • callback execution
  • flush()
  • COMMIT

If the callback or flush fails, ROLLBACK is executed and the original exception is rethrown.

Schema SQL

The SchemaTool generates WordPress-friendly table SQL from entity metadata.

$sql = $schemaTool->getUpdateSchemaSql('sympress-mailer-pro');

For the example EmailLog entity, this produces a CREATE TABLE statement with:

  • prefixed table name
  • mapped columns
  • primary key
  • indexes
  • $wpdb->get_charset_collate()

CREATE TABLE statements are compatible with the migration package's WordPressSqlExecutor, which routes them through dbDelta().

Migration Bridge

When both sympress/orm and sympress/migration are installed, the ORM bridge registers schema migrations automatically during the db_migration_register hook.

Each entity manager group receives one generated migration object. Its version uses a schema hash:

schema:<hash>

When entity metadata changes, the schema hash changes. The migration package treats the changed hash as pending, so the generated schema migration can run again.

The bridge is optional:

  • sympress/orm can run without sympress/migration
  • sympress/migration can run without sympress/orm
  • when both are installed, they cooperate through the bridge

Console Commands

The package exposes commands through the SymPress kernel console integration.

bin/console orm:mapping:info
bin/console orm:mapping:info --manager=sympress-mailer-pro

bin/console orm:schema:sql
bin/console orm:schema:sql sympress-mailer-pro
bin/console orm:schema:sql sympress-mailer-pro --drop

bin/console orm:migrations:diff sympress-mailer-pro \
    --namespace='App\Migration' \
    --path='packages/app/src/Migration'

orm:migrations:diff generates a concrete AbstractMigration class containing the current SQL statements. Use this when you want explicit, reviewable migration files instead of only dynamic schema migrations.

WordPress Compatibility Rules

The ORM is built for custom package tables, not for replacing WordPress core APIs.

Recommended rules:

  • Use WordPress APIs for core tables such as posts, users, terms, options, and comments.
  • Use ORM entities for your own plugin, package, or application tables.
  • Do not replace the global $wpdb.
  • Do not bypass WordPress capabilities, nonces, sanitization, or escaping.
  • Avoid hard foreign keys to WordPress core tables.
  • Keep table names prefix-aware by omitting $wpdb->prefix in #[Entity].
  • Use migrations for schema changes instead of ad-hoc runtime table changes.

Backward Compatibility

From 1.0.0 on the package follows Semantic Versioning: everything not marked @internal is public API, and breaking changes ship only in a major release. Deprecated features trigger E_USER_DEPRECATED in a minor release before they are removed. docs/backward-compatibility.md defines what counts as a breaking change, and UPGRADE.md lists the changes needed to upgrade.

Current Limitations

The package is intentionally small and pragmatic. These features are not part of 1.x so far:

  • lazy references to an inheritance root with subclasses; they load eagerly because the row may be a subclass
  • inheritance mapping beyond single-table inheritance, such as joined/class-table inheritance and table-per-class inheritance
  • Doctrine-style cache concurrency strategies beyond simple cache regions
  • complete Doctrine DQL grammar: subselects, CASE and full AST walkers
  • a persistent second-level or query result cache; caches are request-scoped
  • a streaming Query::toIterable(); wpdb buffers the whole result set
  • cross-vendor platform abstraction beyond the current MySQL/WordPress target

These can be added incrementally without changing the basic entity manager and repository workflow.

Testing

composer install
composer tests

In the root project, the package can also be tested directly:

ddev exec bash -lc 'cd packages/orm && composer install --no-scripts'
ddev exec bash -lc 'cd packages/orm && vendor/bin/phpunit --configuration phpunit.xml.dist --no-coverage'

Local vendor/ and PHPUnit cache directories are ignored by the package .gitignore.

License

This package is licensed under GPL-2.0-or-later.