Transactions

Contents
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

Related articles
Development with PHP
What is Symfony and where it runs
Install Symfony
Your first page
Routes
Controllers
Twig basics
Twig advanced
Doctrine setup
Entities
Migrations
Repositories
Relations
Forms
Validation
Services and DI
JSON controllers
Serializer
Security intro
Users
Login form
Voters
Console commands
Events
Messenger
Mailer
Cache
Sessions
CSRF
Translations
Dotenv and env
Profiler
Testing
Fixtures
Pagination
File uploads
API Platform in one lesson
DQL
Transactions
Migrations advanced
Security advanced
HTTP client
Scheduler
Webhooks
Asset Mapper
Deployment
Performance
Capstone: blog
Capstone: JSON API
Modern Symfony tour
Hero roadmap: the whole course on one page
Banner image

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: