Class: EntityManager
Full name: Azera\Orm\EntityManager
The entity manager: identity map + write pipeline, consolidated.
One instance per request (registered request-scoped in AppContext).
The Active-Record facades (Model,
Document) delegate here, so facade-style and
EM-direct use share ONE write pipeline: diff -> topological order ->
transaction -> ID backfill.
Reads probe the identity map first - find() hit = the same instance, miss = one Store read + FastHydrator onto the shared heap. Works for SQL models (PdoStore) and Mongo documents.
The write pipeline used to be a separate UnitOfWork class; it is merged here because it had exactly one caller and no public surface beyond persist/remove/flush. flush() = diff -> commands -> topological order (owners before dependents, so auto-generated owner PKs backfill into dependents' FK values) -> execute -> backfill IDs -> mark MANAGED, inside the Store's transaction (nested transactions already supported by Database). Fast path: a trivial single-entity flush adds only scheduling overhead, and no tx when one is already open (joins the caller's tx).
Storage-agnostic: writes execute through the Store seam resolved
from class metadata (#[Entity(store: ???)] - an opaque registry key). The
SQL shapes and the RETURNING matrix (pk_set / returning_id /
returning_all / last_insert_id) live in each Store backend; flush
consumes their normalized ['row' => ?array, 'id' => ?scalar] results
for identity backfill.
RequestScoped: resetState() wipes the heap and drops scheduled
writes between requests in persistent workers (non-negotiable - same
contract as Heap).
Public methods
__construct() ·
public function __construct(Azera\Orm\Heap $heap, object|null $db = null): mixed
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$heap |
Heap | - | |
$db |
object|null | null |
Return value
- Type:
mixed
heap() ·
public function heap(): Azera\Orm\Heap
The shared identity map.
Return value
- Type: Heap
find() ·
public function find(string $class, array $id, bool $fresh = false): object|null
Load one entity by PK values: heap probe first, Store read on miss, hydration onto the shared heap.
$fresh=false (default): a heap hit returns the tracked instance WITHOUT touching the store - the identity-map behavior.
$fresh=true: the row is RE-READ from the Store and applied onto the
tracked instance in place (refresh()) - same object, current
values. Use this for stale-read-sensitive work (polling tasks,
cross-request workers between resetState() boundaries). Entities
with scheduled (unflushed) writes must NOT be fresh-read - refresh()
throws instead of silently discarding pending work.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$class |
string | - | |
$id |
array | - | PK field => value |
$fresh |
bool | false |
Return value
- Type:
object|null
findBy() ·
public function findBy(string $class, array $where, bool $fresh = false): array
Load all entities matching field => value conditions.
$fresh=true refreshes already-tracked entities in place from the fresh rows (same instances, current values); entities with pending scheduled writes keep their in-request state.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$class |
string | - | |
$where |
array | - | |
$fresh |
bool | false |
Return value
- Type:
array
refresh() ·
public function refresh(object $entity): object|null
Re-read an entity's row from the Store and refresh the tracked instance IN PLACE: current row values onto the entity, node snapshot synced as the new diff baseline. Identity is preserved - the caller keeps its reference, the data is current. The escape hatch that keeps the identity-map's correctness (one row = one object, no lost in-request writes) while serving freshness-sensitive reads (polling, long-lived workers between request boundaries).
Returns the entity when refreshed. Returns NULL when the row is GONE in storage - the entity is detached (the identity map mirrors the store; a tracked ghost would keep coming back on heap-hit reads). Guards: untracked entities throw (nothing to refresh against - find()/track() first); entities with scheduled unflushed writes throw (a re-read would clobber queued work - flush() first).
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$entity |
object | - |
Return value
- Type:
object|null
persist() ·
public function persist(object $entity): static
Queue an entity for INSERT (or UPDATE when already managed).
Explicit intent - flush() sees ONLY what was persisted here (the deliberate no-implicit-dirty-checking doctrine contrast).
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$entity |
object | - |
Return value
- Type:
static
upsert() ·
public function upsert(object $entity, Azera\Orm\ConflictTarget|null $on = null, array|null $updateColumns = null): static
Queue a single-statement UPSERT (INSERT ... ON CONFLICT DO UPDATE / mongo updateOne upsert:true): the DATABASE resolves insert-vs-update at write time - no prior SELECT, no insert-or-update guess, no unique-violation race. Deliberately intent-based like persist(): the caller asserts "a row with this key should exist afterwards", and the store makes it so atomically.
The conflict target is the PK by default - which requires a full identity (every PK field set); anything less degrades to an ordinary insert. Pass $on to conflict on a DIFFERENT unique key instead:
$em->upsert($customer, ConflictTarget::columns(
['stripe_customer_id'],
'stripe_customer_id IS NOT NULL', // partial index predicate
));
That form is what makes the call idempotent for a table whose PK is database-generated (a uuid the caller has not got yet) and whose real uniqueness lives in a separate index. An explicit target IS a promise, so an unset target column throws rather than quietly inserting.
On a WIDE row the conflict action must be narrowed: writing every non-target column from the payload would clobber state the caller does not own (a credential revision, a counter, a workspace binding). Pass $updateColumns to name exactly what the upsert may change; [] means insert-if-absent and leave an existing row untouched.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$entity |
object | - | |
$on |
ConflictTarget|null | null |
the key to conflict on; null = the PK |
$updateColumns |
array|null | null |
columns the conflict action may write; null = every non-target column in the payload, [] = change nothing |
Return value
- Type:
static
remove() ·
public function remove(object $entity): static
Queue an entity for DELETE.
An UNTRACKED entity is adopted first when its identity is complete: "not in the heap" is not the same as "not in storage", so detaching would report success while leaving the row behind. This makes remove() symmetric with persist() — persist() on an untracked entity inserts, remove() on an untracked entity deletes — instead of the same call meaning "delete" or "do nothing" depending on invisible heap state.
An untracked entity with an INCOMPLETE identity cannot address
anything; adopt() rejects it rather than emitting a
WHERE 1=0 no-op. A pending insert is simply cancelled (nothing
reached storage yet).
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$entity |
object | - |
Return value
- Type:
static
Throws
- LogicException when an untracked entity's identity is incomplete
flush() ·
public function flush(): void
Execute all scheduled writes in ONE transaction (diff -> order -> execute -> backfill).
This is a UNIT-OF-WORK flush: everything queued runs, in dependency
order. Facade save() does NOT use it — it uses
flushEntity(), which writes only what the entity needs. Reach
for flush() when you have deliberately batched several entities and
want them atomic together.
Transaction control follows the SCHEDULED WORK's (store, txTarget)
grouping: all scheduled classes must resolve to ONE store instance
AND one connection target on it - otherwise the flush spans two
connections and cannot be atomic, which throws (stores may relax
this with per-instance semantics via txTarget(); e.g. a mongo
store's no-op txs group under its single instance token). Use
EntityManager::flushAll() for write sets that legitimately
span connections (per-target txs, best-effort all-or-nothing).
Return value
- Type:
void
flushEntity() ·
public function flushEntity(object $entity): bool
Execute ONLY the work scheduled for $entity, leaving every other pending write alone.
This is what save() uses, and the distinction from flush() is
load-bearing. A facade save() means "make THIS row durable". With
a whole-heap flush, one entity's save is silently coupled to every
other entity that happens to be scheduled in the same request, and
a failure in one poisons the other:
$customer->save(); // INSERT customers -> pending $session->save(); // ALSO flushes the customers INSERT
That coupling turned a recoverable duplicate-key write into a webhook 500: saving the checkout session retried an unrelated customer INSERT that had already failed, so the save that was supposed to RECORD the failure threw the same unique violation and the original cause was discarded.
Writes the target cannot proceed without are still honoured: a
belongsTo owner whose generated PK feeds this entity's FK is part
of the same unit of work, so those nodes flush alongside it rather
than being deferred.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$entity |
object | - |
Return value
- Type:
bool - Description: True when this entity actually had something to write
flushAll() ·
public function flushAll(): void
Execute all scheduled writes across EVERY connection they touch.
The escape hatch for write sets that legitimately span multiple stores/connections (e.g. SQL + mongo, or several #[Connection] write roles): ONE global topological pass executes every node (an owner in one group can feed its PK into a dependent in another), and each store/connection target commits its own tx - begun lazily when its first node executes.
Failure semantics are best-effort all-or-nothing, mirroring flush()'s shape: if any write (or a commit) throws mid-pass, every tx begun SO FAR is rolled back; groups whose commit already ran stay committed. Cross-connection atomicity does not exist - use flush() when the whole write set shares one connection target.
Return value
- Type:
void
detach() ·
public function detach(object $entity): void
Drop an entity from identity tracking (no storage effect).
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$entity |
object | - |
Return value
- Type:
void
adopt() ·
public function adopt(object $entity): object
Facade adoption: register an EXTERNALLY-loaded entity as MANAGED with an EMPTY baseline.
Reads that bypass the EM pipeline (FETCH_CLASS ResultSet, Paginator) produce instances that are not in the heap. The facade calls adopt() before persisting. Empty baseline means the next flush writes every set non-PK column - the legacy blind-UPDATE parity for manually built ID'd entities (and the correct semantic: the EM cannot know what the DB already holds for an entity it never loaded).
Entities loaded through EM reads (find/findBy/entities) do NOT need adopt() - their heap node carries the store snapshot from hydration. The returned entity is the ADOPTED instance (heap re-attach replaces the node when the entity already sits under another identity).
THE IDENTITY REQUIREMENT: MANAGED asserts "the row already exists",
so every PK field must be set. A null in the key has no storage
identity, and letting it through corrupts the heap rather than
failing: findById() keys on the null values, WHERE 1=0 makes the
follow-up UPDATE/DELETE a silent no-op, and on a store that filters
by equality (mongo) a partial key can match a DIFFERENT row. Two
entities with NO key at all collapse onto one node. Use persist() for
entities that are not in storage yet — it tolerates a missing key
because it schedules an INSERT (and the heap's synthetic-slot path
keeps those entities apart).
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$entity |
object | - |
Return value
- Type:
object
Throws
- LogicException when any PK field is unset
track() ·
public function track(object $entity): object
Register an externally-loaded entity as MANAGED with its CURRENT values as the baseline (the "already in sync" adoption for entities loaded by reads the EM does not hydrate - FETCH_CLASS ResultSet, Paginator). Unlike adopt(), persist() on a tracked() entity emits SQL only for fields changed after the track() call.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$entity |
object | - |
Return value
- Type:
object
contains() ·
public function contains(object $entity): bool
Whether the entity is tracked in the request heap.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$entity |
object | - |
Return value
- Type:
bool
isScheduled() ·
public function isScheduled(object $entity): bool
Whether the entity has scheduled work in the current flush cycle.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$entity |
object | - |
Return value
- Type:
bool
dirtyData() ·
public function dirtyData(object $entity): array
Dirty state backed by the heap node snapshot (the ONE diff engine ??? Stateful's clone snapshot is gone).
Untracked entity: every metadata column with a set value counts as changed (the same "everything set is pending" semantic the old no-snapshot Stateful path had). Tracked entity: current values vs the node snapshot, field-name-keyed - PK columns EXCLUDED there: identity, not data (the pipeline never puts a PK into an UPDATE SET, so isDirty()/hasChanged() must match what flush() would actually write; a mutated PK on a tracked entity is the identity guard's problem, not a data diff).
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$entity |
object | - |
Return value
- Type:
array - Description: field name => current value
isDirty() ·
public function isDirty(object $entity): bool
Whether the entity differs from its heap baseline (untracked entity: true - it has pending state that adopt+flush would write).
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$entity |
object | - |
Return value
- Type:
bool
revert() ·
public function revert(object $entity): void
Revert the entity's properties to the values recorded in its heap node snapshot (the loadState() replacement). No-op for untracked entities - nothing to revert to.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$entity |
object | - |
Return value
- Type:
void
clear() ·
public function clear(): void
Wipe ALL tracked state (identity + scheduled writes). Scheduled work is dropped, NOT flushed - explicit clear means "forget".
Return value
- Type:
void
resetState() ·
public function resetState(): void
Request-scoped hook: wipe the identity map + any scheduled writes between requests in persistent workers. Also drops the memoized fallback store - a worker re-pointing DatabaseManager roles (tenant swap) must not keep a stale-borrowed store; the next storeFor() rebuilds it from the then-current manager.
Return value
- Type:
void
setStore() ·
public function setStore(string $type, Azera\Orm\Storage\Store $store): static
Register a Store under a TYPE NAME - the single routing axis.
Metadata store (#[Entity(store: ...)]) selects it per class.
A connection-owning backend with multiple clients registers one
type per client ('mongo-eu', 'mongo-us'): the type name IS the
discriminator - there is no role level.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$type |
string | - | |
$store |
Store | - |
Return value
- Type:
static