Skip to content

Add support for object pools / context #12332

@lyrixx

Description

@lyrixx

RFC: Independent Persistence Contexts (Persistence Pools)

Abstract

This RFC proposes a mechanism to create isolated "pools" or "sub-contexts" within the EntityManager. The goal is to allow developers to persist and flush specific entities without interfering with the global UnitOfWork state.

Problem Statement

In many scenarios, developers need to perform "side-effect" writes that are independent of the main business transaction.

Current issues:

  • Global Flush: Calling $em->flush() persists every scheduled change in the UnitOfWork. If the main transaction has pending invalid entities, the side-effect write fails.
  • Partial Flushes: Passing an entity to $em->flush($entity) is deprecated or discouraged because it doesn't guarantee consistency and ignores many UnitOfWork states.
  • Side-effect Rollbacks: If the main transaction fails later, the side-effect (like an audit log) might be rolled back if they share the same underlying transaction/connection.

Use Cases

  • Audit Logging: Persisting call logs or user actions mid-service.
  • Security: Updating a last_used_at timestamp on an API token without flushing the entire user profile.
  • Feature Tracking: Incrementing usage counters during a complex read process.

Proposed Solution

Introduce a Context or Pool object that acts as a lightweight, isolated UnitOfWork.

// Proposed API
$pool = $this->entityManager->createPool();

$log = new AuditLog('AI_CALL', $payload);
$pool->persist($log);

// Only flushes entities managed by this pool
// No interference with the global UnitOfWork
$pool->flush();

Benefits

  1. Isolation: Zero interference with previously scheduled changes in the main EntityManager.
  2. ORM Features: Keeps all advantages (Type conversion, Lifecycle Events, UUID generation).
  3. Developer Experience: Avoids manual SQL queries for "internal" database updates.

Notes

It might be possible with 2 EM, but I'll lead to the same issue. The "internal" EM could have many pending changes

It might be possible with nested transaction, but I'm not sure it has been built for this use case


WDYT ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions