foundation/documentation/unit-of-work.md
2025-06-13 18:29:55 +02:00

1.4 KiB

Unit of Work Pattern

The framework includes a sophisticated Unit of Work pattern for database operations.

Entity Persisters

Entity persisters handle database operations for specific entity types:

class ActivityPersister implements EntityPersisterInterface
{
    public function insert(object $entity, PDO $pdo): void { /* implementation */ }
    public function update(object $entity, PDO $pdo): void { /* implementation */ }
    public function delete(object $entity, PDO $pdo): void { /* implementation */ }
    public function supports(object $entity): bool { return $entity instanceof Activity; }
}

Registration with Inflection

Persisters are registered with UnitOfWork via inflection:

// Register the persister
$container->register(ActivityPersister::class);

// Auto-register with UnitOfWork
$container->inflect(UnitOfWork::class)
          ->invokeMethod('registerPersister', [ActivityPersister::class]);

Usage in Repositories

class ActivityRepository implements ActivityRepositoryInterface
{
    public function save(Activity $activity): void
    {
        if ($activity->getId() > 0) {
            $this->unitOfWork->registerDirty($activity);
        } else {
            $this->unitOfWork->registerNew($activity);
        }
    }

    public function flush(): void
    {
        $this->unitOfWork->commit(); // Executes all operations in single transaction
    }
}