惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Engineering at Meta
Engineering at Meta
The GitHub Blog
The GitHub Blog
博客园_首页
T
The Blog of Author Tim Ferriss
H
Hackread – Cybersecurity News, Data Breaches, AI and More
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
腾讯CDC
I
InfoQ
量子位
J
Java Code Geeks
P
Proofpoint News Feed
有赞技术团队
有赞技术团队
Webroot Blog
Webroot Blog
Martin Fowler
Martin Fowler
D
Docker
F
Fortinet All Blogs
云风的 BLOG
云风的 BLOG
V
Vulnerabilities – Threatpost
罗磊的独立博客
P
Proofpoint News Feed
T
The Exploit Database - CXSecurity.com
Cyberwarzone
Cyberwarzone
P
Privacy & Cybersecurity Law Blog
Last Week in AI
Last Week in AI
爱范儿
爱范儿
The Hacker News
The Hacker News
S
SegmentFault 最新的问题
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 三生石上(FineUI控件)
V
V2EX
Simon Willison's Weblog
Simon Willison's Weblog
AI
AI
Y
Y Combinator Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
GbyAI
GbyAI
V
Visual Studio Blog
H
Heimdal Security Blog
S
Secure Thoughts
B
Blog RSS Feed
雷峰网
雷峰网
T
Tenable Blog
C
Check Point Blog
G
Google Developers Blog
大猫的无限游戏
大猫的无限游戏
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
A
About on SuperTechFans
Recent Commits to openclaw:main
Recent Commits to openclaw:main

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Transactions Without Leaking the Database into Your Domain
Gabriel Anha · 2026-05-19 · via DEV Community

A PlaceOrder use case is sitting on your screen. It writes the order. It reserves stock. It records a ledger entry. Three repositories, three writes, one business intent. If the ledger write fails, the order and the reservation have to vanish with it. Anything less, and a customer ends up with stock held against an order that does not exist.

You know the word for what you need. Atomicity. The database has known it for fifty years. So you reach for the obvious tool.

public function execute(PlaceOrderInput $input): PlaceOrderOutput
{
    return $this->entityManager->wrapInTransaction(
        function () use ($input) {
            $order = Order::place(/* ... */);
            $this->orders->save($order);
            $this->reservations->reserve(/* ... */);
            $this->ledger->record(/* ... */);
            return new PlaceOrderOutput($order->id->value);
        }
    );
}

Enter fullscreen mode Exit fullscreen mode

It works. Tests go green, code review nods it through, you move on to the next ticket.

You also just made a mistake. The use case now imports Doctrine\ORM\EntityManagerInterface. The application layer, the part you were supposed to keep ignorant of the database, has Doctrine in its constructor. Every other use case will copy the pattern, because copy-paste is how patterns spread. Three months from now the application has dozens of references to EntityManager and one of your engineers is asking if you can move a slice of the system to MongoDB.

You cannot. Not cheaply.

This post is about getting atomicity without paying that price.

A use case wrapped in a transactional decorator at the composition root

What the problem actually is

Transactions are an infrastructure concept. They live in the database, the driver, the ORM. The application layer needs the guarantee (all writes succeed together or none do) but it does not need the mechanism. The Dependency Rule says outer rings depend inward; inner rings know nothing of the outer. A PlaceOrder that calls EntityManager::wrapInTransaction inverts that. The use case is reaching outward into Doctrine.

The cost shows up first in testability. Every test for PlaceOrder now needs a real or mocked EntityManager. The unit tests with in-memory repositories and no database at all stop being unit tests. They become integration tests with extra steps.

It also shows up in portability. The word makes the problem sound grander than it is. "Switch ORMs" reads like something only architects in slide decks worry about. The real version is smaller. You want to run a use case from a CLI script against raw DBAL. You want a worker process that wires Doctrine differently. You want a test harness that runs the use case against an in-memory state machine. All of those break when EntityManager is welded to the use case.

You want the guarantee without the import.

Option 1: a UnitOfWork port

You write an interface in the application layer that expresses the transaction boundary in your own vocabulary. The implementation lives at the edge.

<?php

declare(strict_types=1);

namespace App\Application\Port;

interface UnitOfWork
{
    /**
     * @template T
     * @param callable(): T $work
     * @return T
     */
    public function wrap(callable $work): mixed;
}

Enter fullscreen mode Exit fullscreen mode

One method. The contract is plain: run the callable, and if it returns, the writes are durable; if it throws, the writes are undone and the exception propagates.

Notice what is missing. No begin, no commit, no rollback. Those exist in the adapter. The application never sees them, because there is no reasonable case for application code to start a transaction without also being responsible for ending it. You can construct hypotheticals, but they tend to dissolve back into a design smell once you look closely.

The Doctrine adapter is six lines.

<?php

declare(strict_types=1);

namespace App\Infrastructure\Persistence\Doctrine;

use App\Application\Port\UnitOfWork;
use Doctrine\ORM\EntityManagerInterface;

final readonly class DoctrineUnitOfWork implements UnitOfWork
{
    public function __construct(
        private EntityManagerInterface $em,
    ) {}

    public function wrap(callable $work): mixed
    {
        return $this->em->wrapInTransaction(
            static fn () => $work(),
        );
    }
}

Enter fullscreen mode Exit fullscreen mode

wrapInTransaction is the Doctrine 3 successor to the deprecated transactional. It opens a transaction on the underlying DBAL connection, runs the callable, flushes the EntityManager, commits on clean return, and on exception rolls back, closes the EntityManager, and re-throws the original error.

The Laravel adapter is also six lines (it calls DB::transaction($work)). The Symfony version wraps a Connection::transactional. You can write a PDO-only version that calls beginTransaction, commit, rollBack by hand. Same port, four different adapters, zero changes in the application layer.

The downside: you wrote and now maintain a port. One more file, one more abstraction in the stack trace.

The upside is bigger than it looks. The port composes with a decorator, and that is where the real win lives.

Option 2: a transactional decorator at the wiring level

The use case stays exactly as it was on the day you wrote it, before you knew transactions existed. It takes its repositories. It calls them. It returns. The transaction is composed at the boundary.

<?php

declare(strict_types=1);

namespace App\Application\Decorator;

use App\Application\Port\UnitOfWork;
use App\Application\UseCase;

final readonly class TransactionalDecorator implements UseCase
{
    public function __construct(
        private UseCase $inner,
        private UnitOfWork $unitOfWork,
    ) {}

    public function execute(mixed $input): mixed
    {
        return $this->unitOfWork->wrap(
            fn () => $this->inner->execute($input),
        );
    }
}

Enter fullscreen mode Exit fullscreen mode

That is the whole class. It is the decorator pattern from the Gang of Four book, applied to use cases. The decorator implements the same interface as the thing it wraps, holds an instance of that thing, and adds behavior around the inner call. Here the added behavior is a transaction.

In the container, you bind PlaceOrder::class to a factory that builds the inner PlaceOrder and wraps it.

$inner = new PlaceOrder($orders, $reservations, $ledger);
$useCase = new TransactionalDecorator(
    $inner,
    $unitOfWork,
);

Enter fullscreen mode Exit fullscreen mode

Callers ask the container for a PlaceOrder and get a decorated one. They do not know. They should not care. The HTTP controller, the CLI command, the queue worker all receive the same wrapped instance.

This is the option to reach for first, mostly because of what it prevents. PlaceOrder has no UnitOfWork in its constructor, so it cannot accidentally call begin and forget to call commit. It cannot half-commit a transaction by catching an exception it should not have caught. The boundary is enforced by composition, not by discipline (which, given enough engineers and enough deadlines, always loses).

Decoration also composes. You can stack a LoggingDecorator, a MetricsDecorator, a RetryDecorator, and a TransactionalDecorator in whatever order makes sense:

$inner       = new PlaceOrder($orders, $reservations, $ledger);
$transacted  = new TransactionalDecorator($inner, $unitOfWork);
$retried     = new RetryDecorator($transacted, maxAttempts: 3);
$metered     = new MetricsDecorator($retried, $metrics);
$logged      = new LoggingDecorator($metered, $logger);

Enter fullscreen mode Exit fullscreen mode

Logging usually wraps the whole thing because you want to see the call even when the transaction rolled back. Retries wrap the transactional decorator so each retry is its own transaction. Metrics record either side depending on what you want to measure. The use case stays one class with one responsibility, and the cross-cutting concerns live as siblings around it.

Where the pattern frays: long-running operations (a six-second report, an external API call that takes its time) should not be inside a database transaction, so they should not be decorated. Distributed transactions across two databases are not what the decorator gives you; it wraps one connection.

Those cases need different machinery. For everything else, the port-plus-decorator pair is the answer.

Option 3: the pragmatic one — let the application know Doctrine flushes

You see this in production Laravel and Symfony codebases that have not yet adopted hexagonal architecture, or have adopted it partially. The use case calls $this->entityManager->flush() at the end, and a higher-level controller or middleware opens the transaction.

public function execute(PlaceOrderInput $input): PlaceOrderOutput
{
    $order = Order::place(/* ... */);
    $this->orders->save($order);
    $this->reservations->reserve(/* ... */);
    $this->ledger->record(/* ... */);
    $this->entityManager->flush();

    return new PlaceOrderOutput($order->id->value);
}

Enter fullscreen mode Exit fullscreen mode

This works. Doctrine batches the writes until flush. If you opened a transaction at the controller level (or relied on wrapInTransaction somewhere above), the flush either commits or rolls back as one unit. You skipped writing a port. You have one less interface to teach to new hires.

The cost is that "the application calls flush" is now part of the contract. flush is a Doctrine method. Your application layer imports EntityManagerInterface. You traded a port for a leak. If you ever swap Doctrine out (a CQRS write side that uses raw DBAL, a different ORM, a test harness) every use case that calls flush is now framework-coupled and has to change.

For a single-team service that will live and die on Doctrine, this approach is fine. For a service that you expect to outlive its current persistence stack, it is debt that you will pay later.

It is included here because pretending it does not exist would misrepresent what runs in production. Plenty of working systems use it. Use it with eyes open.

Rollback flow when an exception propagates through the decorator

Rollback semantics worth being precise about

When the adapter rolls back, here is what actually happens.

The database transaction reverses. Every INSERT, UPDATE, and DELETE issued inside the wrapped callable is gone as if it never happened.

The EntityManager is closed. Doctrine's identity map is in a known-bad state after a rollback (it may still hold managed entities that no longer exist in the database) so the ORM defensively shuts the EntityManager. If you wire the EntityManager as a long-lived singleton, handle reset between requests, or use a factory that returns a fresh instance after each rollback. Most modern frameworks handle this automatically when EM lifetime is scoped per request.

The exception keeps its identity. A DomainException thrown from the inner use case arrives at the outer caller as the same DomainException, not wrapped, not transformed. Domain exceptions cross the boundary unchanged so the HTTP adapter can translate them properly. The UnitOfWork port does not catch and rethrow, it does not wrap; it lets the exception go past it on the way out.

The application code at the controller level sees a clean picture. Either $useCase->execute($input) returned a value, in which case the writes are committed, or it threw, in which case they are not. No "partially committed," no "succeeded but didn't flush." That binary is the guarantee you were after when you started reaching for transactions in the first place.

Nested transactions: do not

You will eventually find yourself with a use case that calls another use case. Both are wrapped in TransactionalDecorator. What happens?

The Doctrine answer is technically savepoints. wrapInTransaction detects an open transaction on the underlying connection and uses a savepoint for the nested call. The outer transaction owns the real commit. The inner savepoint can roll back independently.

The practical answer: do not rely on this. Savepoints are not free; they generate extra round-trips and locks. Their semantics across database engines are not uniform. Postgres behaves differently from MySQL, which behaves differently from SQLite. Your test infrastructure may not reproduce production behavior. And worse, nested transactional use cases usually mean you have a composition problem: an "orchestrator" use case that should probably be split, or a use case calling another use case directly when it should be emitting an event.

One transaction boundary per inbound call. The controller invokes one decorated use case. That use case may internally call domain services, may emit domain events, may write to multiple repositories, but it stays inside the one transaction the decorator opened. If you need cross-aggregate work that cannot fit, you do not nest. You decompose, and the second operation runs in its own transaction, triggered by an event.

A reflection test that keeps the boundary honest

Architectural rules you do not enforce in code tend to drift, and the drift is invisible until you trip over it during a refactor. The smallest possible enforcement for "the application layer does not know about transactions" is a reflection test.

<?php

declare(strict_types=1);

namespace Tests\Architecture;

use App\Application\UseCase\PlaceOrder\PlaceOrder;
use PHPUnit\Framework\TestCase;
use ReflectionClass;

final class PlaceOrderIsTransactionAgnosticTest extends TestCase
{
    public function test_does_not_depend_on_transaction_machinery(): void
    {
        $forbidden = [
            'EntityManager',
            'wrapInTransaction',
            'beginTransaction',
            '->flush(',
            'commit(',
            'rollBack',
        ];

        $source = file_get_contents(
            (new ReflectionClass(PlaceOrder::class))
                ->getFileName(),
        );

        foreach ($forbidden as $token) {
            self::assertStringNotContainsString(
                $token,
                $source,
                sprintf(
                    'PlaceOrder leaked persistence concern: %s',
                    $token,
                ),
            );
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

The next engineer who reaches for the obvious-but-wrong solution sees this test fail in CI before the pull request gets a human reviewer. Steal it. Adapt it. Add similar guards for the other invariants you care about.

The honest trade-off

The decorator-plus-port approach is what most production codebases that have lived through a framework migration end up with, but it is not free.

The bill: one extra class per cross-cutting concern (the decorator), one extra interface for the port, plus DI configuration to bind them together. Every framework has its own dialect (Symfony's decoration tags, Laravel's app->bind callbacks, raw containers' factories). Stack traces from a wrapped use case include the decorator frame. That makes debugging marginally noisier. New engineers need to be told why a class named PlaceOrder is actually a TransactionalDecorator at runtime, because their IDE does not show that.

The pragmatic approach is faster to write and easier to explain on day one. $em->flush() at the bottom of every use case is two words. Anyone who knows Doctrine reads it instantly. No port, no decorator, no DI gymnastics. The cost is invisible until the day you want to evolve away from Doctrine, and by then the cost is dozens of files.

The middle ground (the port without the decorator) exists but is weakly motivated. If the port is already written, the decorator is free. Spreading $this->unitOfWork->wrap(...) calls across every use case when one decorator handles it once gains nothing. The only situation where the bare port makes sense is when some use cases need to not be transactional (long-running reports, idempotent reads), in which case you decorate the ones that need it and leave the rest alone.

Pick based on the lifespan you expect from the application. Code that will exist for three years and then be replaced: pragmatic. Code that you expect to keep running for a decade through framework upgrades and ORM migrations: port plus decorator.

What the use case never knew

Step back and notice what you built.

PlaceOrder is forty-something lines. It takes three repositories, calls them, returns. No transaction code, no ORM imports, no awareness of when a flush happens or what driver underpins the storage.

It is also fully atomic in production, fully testable without a database, and free to be wired into a CLI script, a queue worker, an HTTP controller, or a test harness with no changes. The behavior you wanted (all writes succeed together or none do) sits one layer above the class. That layer is the decorator. The decorator delegates to a port. The port has two implementations: one for Doctrine, one for tests.

If next year you replace Doctrine with raw DBAL, you write a new adapter and PlaceOrder does not change. Add MongoDB for some aggregates the year after, and you write a third adapter that holds a session and uses Mongo's transactional API; the use case still does not notice.

Transactions feel inherently database-y, which is why people stop trying to abstract them. The abstraction is small: a port, an adapter, and a decorator. You can have atomicity and decoupling at the same time. The cost is three files.


If this was useful

This is one chapter from Decoupled PHP — the book about treating Laravel or Symfony as an adapter and writing the rest of your application against ports it owns. The transaction chapter pairs with a chapter on the outbox pattern for the cases where one transaction is not enough, and a chapter on testing the hexagon without booting a container. If you want the database side of the story (picking the right store, designing schemas that survive growth, the actual trade-offs across Postgres, MySQL, MongoDB, DynamoDB) the Database Playbook is the companion volume.

Decoupled PHP — Clean and Hexagonal Architecture for Applications That Outlive the Framework

Available on Kindle, Paperback, and Hardcover. English, German, and Japanese editions out now — Portuguese and Spanish coming soon.