andreybolonin / modernorm
PostgreSQL-first ORM for PHP with a focus on fetching, caching and observability.
Requires
- php: ^8.4
- ext-pdo: *
- ext-pdo_pgsql: *
- doctrine/collections: ^3.1
- doctrine/dbal: ^4.6
- doctrine/deprecations: ^1
- doctrine/event-manager: ^2.1.1
- doctrine/persistence: ^4
- psr/cache: ^3
Requires (Dev)
- ext-ctype: *
- friendsofphp/php-cs-fixer: ^3.90
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^11.5
- psr/log: ^3
- symfony/cache: ^7.4
- symfony/console: ^7.4
Suggests
- ext-deepclone: >=0.8.13: accelerates flat entity hydration with deepclone_hydrate()
- symfony/cache: PSR-6 adapters for filesystem, Redis and other cache backends
- symfony/console: ^7.4 || ^8.0: enables optional CLI tools
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-24 16:51:05 UTC
README
PostgreSQL-first ORM for PHP 8.4+.
Batch fetching, PostgreSQL bulk writes, entity L2 cache and built-in observability — designed for ERP and data-heavy applications.
100 orders. 100 distinct customers. 101 SELECTs → 5 with batch size 32. Measured workload.
Built for demanding persistence workloads
| Feature | What you get |
|---|---|
| Batch fetching | Load lazy ManyToOne, OneToMany and ManyToMany associations in groups, configured directly on attributes. |
| Native hydration acceleration | Automatically use deepclone_hydrate() from optional ext-deepclone for eligible scalar fields and large embedded batches, with accessor fallback. |
| PostgreSQL-native bulk | Multi-row INSERT, UPSERT, UPDATE, DELETE and RETURNING, with explicit UnitOfWork policies. |
| Entity L2 cache | Cache entities across EntityManagers with PSR-6 storage, TTL and generation-based invalidation. |
| Association Query API | Count, check membership, filter and paginate OneToMany/ManyToMany directly in SQL without loading collections. |
| Keyset pagination | Traverse large entity queries with forward/backward cursors, explicit sort fields and an optional lazy total count. |
| Full-text search | Declare weighted STORED search vectors and GIN indexes with FullTextIndex; search, rank and retrieve relevance scores through QueryBuilder. |
| Declarative PostgreSQL schema | Declare CHECK constraints with #[Check], row triggers with #[Trigger], and exclusion constraints with #[Exclude]. |
| JSONB Query API | Filter mapped JSONB fields with containment, key existence, paths and typed comparisons, with automatic parameter binding and explicit null semantics. |
| SQL-first queries | PostgreSQL expressions and CTEs, with managed entity hydration or plain rows. |
| Built-in behaviors | Timestampable, Blameable and SoftDelete built in — no extra behavior package required. |
| Built-in Statistics API | Measure SQL, flush, batch, bulk, hydration and UnitOfWork phases; consume neutral operation events. |
PHP attributes, native lazy objects, Identity Map and UnitOfWork keep ordinary entity persistence familiar.
Declare stored PostgreSQL search vectors and GIN indexes with #[FullTextIndex]; search and rank through the existing SQL API.
Behaviors are explicitly enabled per entity: Timestampable, Blameable and SoftDelete. Beta.5 includes Timestampable, the Blameable provider/listener API and SoftDelete.
Fewer queries. The same entity workflow.
Set the batch size on a relation, then access it normally:
use ModernORM\Mapping as ORM; #[ORM\Entity] class Order { // Identifier and other fields omitted. #[ORM\ManyToOne(targetEntity: Customer::class, batchSize: 32)] public Customer $customer; } $orders = $em->getRepository(Order::class)->findBy([], ['id' => 'ASC']); foreach ($orders as $order) { echo $order->customer->name; }
Accessing a queued reference loads compatible references together through an IN query. OneToMany and ManyToMany also accept batchSize; the ORM distributes results across their owner collections.
Batching is opt-in. Association settings override the global default, and batchSize: 1 disables batching for that relation. Batch fetching · OneToMany · ManyToMany.
Bulk writes for imports and mass changes
use ModernORM\Bulk\BulkPolicy; $result = $em->bulk()->upsert(Product::class, [ ['sku' => 'A', 'price' => '12.50'], ['sku' => 'B', 'price' => '15.00'], ], conflictFields: ['sku'], updateFields: ['price'], policy: BulkPolicy::CLEAR, returning: ['id', 'sku']);
Choose BYPASS to leave managed state unchanged, or CLEAR to detach the entire context and discard pending work after success. Bulk operations skip per-row ORM callbacks and do not flush pending changes automatically.
Bulk API · Recorded timings, memory and methodology.
Cache reference data across requests
use ModernORM\Cache\CacheWritePolicy; use ModernORM\Mapping as ORM; #[ORM\Entity] #[ORM\Cacheable(ttl: 3600, writePolicy: CacheWritePolicy::INVALIDATE)] class Currency { #[ORM\Id, ORM\Column(length: 3)] public string $code; #[ORM\Column] public string $name; } $config->setSecondLevelCache($pool, namespace: 'app_l2_v1');
Use a PSR-6 pool for entity-by-ID caching. INVALIDATE permits ORM updates with pre-write/post-commit invalidation; the default READ_ONLY policy rejects ORM updates. The current cache scope is entities without declared associations.
#[ORM\Immutable] separately skips entity field updates while preserving INSERT and DELETE. L2 cache · Supported scenarios · Immutable entities.
Query PostgreSQL. Get entities or rows.
$query = $em->createQueryBuilder()->fromEntity(Project::class, 'p'); $projects = $query ->where($query->column('p', 'name').' = :name') ->setParameter('name', 'alpha') ->getQuery() ->getResult();
Build SQL directly while retaining entity hydration and the Identity Map. Use DBAL-style row queries when managed objects are unnecessary. SQL query API.
See what your ORM does
Enable Statistics to inspect operation counts, timings, errors and batch sizes without a monitoring backend:
$snapshot = $em->getStatistics()->snapshot(); $snapshot->sqlCount; $snapshot->sqlTimeMilliseconds(); $snapshot->batch->count; $snapshot->bulk->affectedRows;
Statistics setup · Operation events.
With ModernORMBundle, inspect eight Symfony Profiler tabs and a Performance Advisor with recommendations linked to the relevant queries and panels.
Real demonstration workload; displayed timings are not benchmark results. The bundle also includes an opt-in OpenTelemetry → Collector → VictoriaMetrics → Grafana prototype.
Focused by design
| Capability | ModernORM | Another ORM |
|---|---|---|
| Database | PostgreSQL only | Multiple databases through DBAL |
| Queries | SQL QueryBuilder with entity hydration | DQL QueryBuilder and native SQL |
| Association loading | Lazy batching for ManyToOne, OneToMany and ManyToMany | Fetch joins and eager to-one batching |
| L2 cache | Entity-by-ID, PSR-6, Cacheable attribute |
Entity, collection and query cache regions |
| Statistics | SQL, flush, batch, bulk, hydration and UnitOfWork events | DBAL instrumentation and L2-specific statistics |
| Mapping | Attributes and one scalar entity PK | Multiple drivers, inheritance and composite IDs |
DQL, entity inheritance, composite entity IDs, XML/YAML mapping, ORM Filters and Criteria SQL translation are intentionally excluded. MappedSuperclass, embeddables, lifecycle callbacks, cascades, orphan removal and basic locking remain available. Mapping scope · Compatibility.
Confirmed inherited bugs
These behaviors were reproduced on ModernORM before the persistence, PostgreSQL write-path and Identity Map audits; the corresponding mechanisms were checked against the Doctrine ORM 3.7.6 sources from which ModernORM was derived. Fixed means covered by ModernORM regressions and included in beta.5. Upstream links identify provenance, not the current status of a Doctrine fix.
| Confirmed bug | Upstream reference | ModernORM status |
|---|---|---|
| Replacing an orphan-removal collection deletes retained/transferred children; whole-collection deletion skips entity removal callbacks | #6999, #12642 | Fixed — compare membership and remove only actual orphans through entity lifecycle |
remove() / removeElement() deletes a child still held under another collection key |
#12642 | Fixed — recheck remaining membership |
set() over an occupied key does not orphan the displaced entity |
#12641 | Fixed — orphan the displaced member only if it is no longer present; UNIQUE ordering remains a separate limitation below |
| Loading an inverse collection overwrites an explicitly changed owning-side reference | PersistentCollection source | Fixed — preserve owning-side changes during hydration |
EXTRA_LAZY get(id) returns a target belonging to another owner, including ManyToMany associations |
#8607, PersistentCollection source | Removed — EXTRA_LAZY is no longer supported; use Association Query API |
| EXTRA_LAZY indexed lookup on unidirectional ManyToMany requires a nonexistent inverse property | ManyToManyPersister source | Removed — EXTRA_LAZY is no longer supported; indexed LAZY collections remain available |
onFlush loses explicitly computed INSERTs/UPDATEs when the initial queue is empty |
UnitOfWork source | Fixed — recheck pending operations after the event |
An exception from postFlush skips cleanup of completed flush state |
UnitOfWork source | Fixed — completed state is cleared before callbacks; new work survives for the next flush and an already committed transaction stays committed |
| Identity INSERT can assign a different sequence's value after a trigger advances it | IdentityGenerator source | Fixed — standard identity INSERT reads its own identifier through RETURNING |
| A trigger-suppressed identity INSERT can register an entity for a nonexistent row | BasicEntityPersister source | Fixed — missing RETURNING row fails flush and closes the manager |
| A rejected object with a duplicate ID can pass membership checks and evict the registered instance through removal/detach | UnitOfWork source | Fixed — membership and removal require the exact registered object |
| Removing a row and inserting its replacement with the same immediate UNIQUE value fails in one flush | #5109 | Open — documented limitation: INSERT precedes DELETE; use two flushes in one transaction or a suitable deferred UNIQUE constraint |
| Swapping two immediate UNIQUE values fails on an intermediate UPDATE | Update execution source | Open — documented limitation: no automatic conflict-resolution plan; suitable deferred constraints require an explicit migration |
Audit, contracts and per-bug tests · PostgreSQL write-path audit · Identity Map audit · Before/after evidence: 36 scenarios, 23 failing before, all passing after. Scenario counts are not independent bug counts; limitation tests assert the expected failure. This is a confirmed list, not an exhaustive inventory of Doctrine issues. Nested-flush rejection, manual rollback boundaries and excluded SoftDelete combinations are tracked separately in the audit.
Install & get started
Requires PHP 8.4+, DBAL 4.6+ (4.x), PostgreSQL and pdo_pgsql.
Custom types can be scoped to each connection: DBAL type providers.
composer require 'andreybolonin/modernorm:^0.1@beta'
Start with the executable persistence example, or use ModernORMBundle for Symfony, migrations, fixtures and Profiler integration. Code excerpts above assume configured services and mapped entities.
The current 1.0 prerelease is 1.0.0-rc.2. The beta line remains available. See the beta contract for the beta line and the 1.0 candidate guide for the matching bundle version and upgrade steps.
Documentation · Benchmarks · Roadmap · Changelog · Contributing · Security.
License
MIT. Derived from Doctrine ORM; original third-party notices are preserved in licenses/.
