Skip to content

Transaction

The Transaction plugin provides database transaction management, ensuring atomicity of operations with automatic rollback on failure.

Four adapters are available:

  • InMemoryTransaction provides a no-op implementation for testing.
  • SqliteTransaction manages SQLite database transactions.
  • MysqlTransaction manages MySQL database transactions.
  • PostgresqlTransaction manages PostgreSQL database transactions.

Why Use It

Database operations that span multiple writes must be atomic. The Transaction plugin ensures all operations succeed together or fail together, preventing partial updates that leave the database in an inconsistent state.

The primary usage is through TransactionalCommandBus, which automatically wraps command execution in a transaction.

Usage

The TransactionalCommandBus handles transactions automatically:

// Commands are automatically wrapped in transactions
$this->commandBus->dispatch(new CreateBookCommand(...));

For manual transaction control:

$this->transaction->begin();
try {
    $this->bookRepository->save($book);
    $this->transaction->commit();
} catch (Throwable $e) {
    $this->transaction->rollback();
    throw $e;
}

Nested calls are handled gracefully—the bus detects existing transactions and reuses them.

Testing

The InMemoryTransaction adapter tracks transaction state without database operations:

$transaction = new InMemoryTransaction();
$transaction->begin();
// Operations execute without actual transactions
$transaction->commit();

See Also