begin_transaction(); } public function commitTransaction(): void { DB::handle()->commit(); } public function rollbackTransaction(): void { DB::handle()->rollback(); } /** * Run a callback inside a DB transaction. Commits on success, rolls back on exception. * * Eliminates the need for manual begin/commit/rollback + rollbackQuietly() boilerplate * that is duplicated across multiple services. The callback receives no arguments; * use closures to capture dependencies. * * @template T * @param callable(): T $callback * @return T The value returned by the callback. * @throws \Throwable Re-throws the original exception after rollback. */ public function transaction(callable $callback): mixed { $this->beginTransaction(); try { $result = $callback(); $this->commitTransaction(); return $result; } catch (\Throwable $e) { try { $this->rollbackTransaction(); } catch (\Throwable) { // Swallow — the original exception is more important. } throw $e; } } }