Transactions
| Wrap in transaction | |
| Rollback on catch | |
| Isolation note | |
| Nested note |
Wrap in transaction
Some writes belong together: order plus payment, or user plus profile. Either all land or none land.
The wrapper below runs the closure inside one transaction. A throw anywhere rolls everything back.
$manager->wrapInTransaction(function () use ($manager, $user): void { $manager->persist($user); $manager->flush(); });
Rollback on catch
For longer flows use begin, commit, and rollback by hand. Commit only after the last write succeeds.
The catch block rolls back and rethrows. The caller still sees the error, but the base stays clean.
$manager->beginTransaction(); try { $manager->persist($user); $manager->flush(); $manager->commit(); } catch (Exception $e) { $manager->rollback(); throw $e; }
Isolation note
Parallel requests can step on each other between read and write. Isolation levels decide what one deal sees of another.
Default levels fit most apps. Raise the level only after a real race shows up in logs.
Nested note
Nested deals do not truly nest in most setups. Inner commits ride along with the outer one until it commits.
Savepoints can fake nesting for one risky part. Keep nesting shallow so the flow stays readable.
Next: Migrations advanced
Article author: Arthur Isaev