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

推荐订阅源

Google DeepMind News
Google DeepMind News
Jina AI
Jina AI
IT之家
IT之家
J
Java Code Geeks
博客园_首页
Stack Overflow Blog
Stack Overflow Blog
量子位
I
InfoQ
博客园 - 【当耐特】
阮一峰的网络日志
阮一峰的网络日志
WordPress大学
WordPress大学
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 司徒正美
V
V2EX
博客园 - Franky
U
Unit 42
S
SegmentFault 最新的问题
美团技术团队
The Register - Security
The Register - Security
Last Week in AI
Last Week in AI
G
Google Developers Blog
aimingoo的专栏
aimingoo的专栏
博客园 - 叶小钗
M
MIT News - Artificial intelligence
博客园 - 聂微东
腾讯CDC
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
T
Troy Hunt's Blog
B
Blog
P
Palo Alto Networks Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Privacy International News Feed
K
Kaspersky official blog
The GitHub Blog
The GitHub Blog
C
Cisco Blogs
Microsoft Azure Blog
Microsoft Azure Blog
F
Fortinet All Blogs
S
Schneier on Security
C
CERT Recently Published Vulnerability Notes
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Engineering at Meta
Engineering at Meta
TaoSecurity Blog
TaoSecurity Blog
小众软件
小众软件
T
Threatpost
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Martin Fowler
Martin Fowler
AWS News Blog
AWS News Blog
V
Visual Studio Blog
Simon Willison's Weblog
Simon Willison's Weblog
H
Heimdal Security Blog

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
Symfony Is Also an Adapter (Yes, Even With All Its Glue)
Gabriel Anha · 2026-05-19 · via DEV Community

A four-year-old Symfony codebase has a different smell than a four-year-old Laravel one. The controllers are thinner, the repositories already exist as classes, and the container is wired with attributes rather than facade calls. From a distance, the team looks like it has been doing architecture all along.

That distance is the trap.

Open the entity. The Doctrine class has #[PrePersist] doing tax math. The repository extends ServiceEntityRepository and returns live entities with lazy collections still attached. The "service" layer is three classes deep (OrderService calls OrderManager calls OrderProcessor), and somewhere in that chain a private method decides whether a refund is legal. The controller extends AbstractController, accepts a Request, and trusts the service to figure it out.

None of that is wrong by Symfony's own standards. It is just framework-coupled all the way down. And the fix is the same exercise you do with Laravel: stop pretending Symfony is the application, and start treating it like what it is: a very capable adapter.

The shape you're aiming at

The end state is a directory tree where the domain has no idea Symfony exists.

src/
├── Domain/
│   └── Order/              # plain PHP, no Symfony, no Doctrine
├── Application/
│   └── Order/              # use cases, ports as interfaces
└── Infrastructure/
    ├── Http/               # Symfony controllers
    ├── Messenger/          # Messenger handlers
    └── Persistence/
        └── Doctrine/       # adapters + OrderRecord

Enter fullscreen mode Exit fullscreen mode

The rule that makes the layout work is the import graph:

  • Domain/ imports nothing from the project. Pure PHP.
  • Application/ imports Domain/ (ports name domain types).
  • Infrastructure/ imports Application/ and Domain/ (it implements the ports and converts between framework types and domain types).
  • config/services.yaml is the only place that knows about both sides.

If your Domain/ ever imports Symfony\* or Doctrine\*, the architecture is leaking. One CI check catches it:

! grep -rE "use (Symfony|Doctrine)\\\\" src/Domain/ \
  || (echo "FAIL: domain imports framework" && exit 1)

Enter fullscreen mode Exit fullscreen mode

The hexagon, with Symfony on the outside

The starting point, in honest detail

Here is the controller most Symfony teams ship. The smells are not subtle.

namespace App\Controller;

use App\Entity\Order;
use App\Repository\OrderRepository;
use App\Service\OrderManager;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;

class OrderController extends AbstractController
{
    public function __construct(
        private EntityManagerInterface $em,
        private OrderRepository $orders,
        private OrderManager $orderManager,
    ) {}

    #[Route('/orders', methods: ['POST'])]
    public function create(Request $request): JsonResponse
    {
        $payload = json_decode($request->getContent(), true);

        $this->em->beginTransaction();
        try {
            $order = new Order();
            $order->setCustomerId($payload['customer_id']);
            $order->setStatus('pending');

            $subtotal = 0;
            foreach ($payload['items'] as $line) {
                $item = new OrderItem();
                $item->setSku($line['sku']);
                $item->setQuantity($line['qty']);
                $order->addItem($item);
                $subtotal += $line['price'] * $line['qty'];
            }
            $order->setSubtotalCents($subtotal);

            $this->orderManager->finalize($order);

            $this->em->persist($order);
            $this->em->flush();
            $this->em->commit();
        } catch (\Throwable $e) {
            $this->em->rollback();
            return new JsonResponse(['error' => $e->getMessage()], 422);
        }

        return new JsonResponse([
            'id' => $order->getId(),
            'total' => $order->getTotalCents() / 100,
        ], 201);
    }
}

Enter fullscreen mode Exit fullscreen mode

The controller extends AbstractController. It validates HTTP, walks a cart, applies a coupon rule, delegates the rest to a service chain, and commits a transaction. The "real work" is hidden behind $this->orderManager->finalize($order) — a method that does tax, audit, and warehouse notification.

The entity is no better:

#[ORM\Entity(repositoryClass: OrderRepository::class)]
#[ORM\HasLifecycleCallbacks]
class Order
{
    #[ORM\Id, ORM\GeneratedValue, ORM\Column]
    private ?int $id = null;

    #[ORM\Column] private int $subtotalCents = 0;
    #[ORM\Column] private int $totalCents = 0;

    #[ORM\PrePersist]
    public function applyTax(): void
    {
        $tax = (int) round($this->subtotalCents * 0.21);
        $this->totalCents = $this->subtotalCents + $tax;
    }
}

Enter fullscreen mode Exit fullscreen mode

Tax is the most domain-flavored code in the system, and it lives inside a Doctrine event hook. To unit-test it you need an EntityManager. To run it from a queue worker you have to flush. To run it during a price recalculation job you have to copy the body.

Every test against this controller boots the kernel.

The domain doesn't extend AbstractController

The first thing that changes is the entity. You write a pure-PHP Order next to the Doctrine one. No attributes, no extends, no Doctrine collections. Just behavior and value objects.

namespace App\Domain\Order;

final class Order
{
    private function __construct(
        public readonly OrderId $id,
        public readonly CustomerId $customerId,
        private array $items,
        private Money $total,
        private OrderStatus $status,
    ) {}

    public static function place(
        OrderId $id,
        CustomerId $customerId,
        array $items,
        TaxPolicy $tax,
    ): self {
        if ($items === []) {
            throw new EmptyCartException();
        }

        $subtotal = Money::sum(
            array_map(fn(LineItem $i) => $i->total(), $items),
        );

        return new self(
            $id,
            $customerId,
            $items,
            $tax->apply($subtotal),
            OrderStatus::Pending,
        );
    }

    public function total(): Money
    {
        return $this->total;
    }
}

Enter fullscreen mode Exit fullscreen mode

There is no EntityManagerInterface. No Request. No AbstractController. Order::place() is callable from anywhere — a controller, a Messenger handler, a CLI command, a test. It does not care which one called it.

The port follows the same rule:

namespace App\Domain\Order;

interface OrderRepository
{
    public function find(OrderId $id): ?Order;
    public function save(Order $order): void;
}

Enter fullscreen mode Exit fullscreen mode

No Doctrine\Persistence\ManagerRegistry in the constructor. No ServiceEntityRepository parent. The domain says what persistence looks like. The adapter figures out how.

The use case is the application

The use case is the class that orchestrates the domain. It lives in App\Application\Order\PlaceOrder and it imports zero Symfony namespaces.

namespace App\Application\Order;

use App\Domain\Order\Order;
use App\Domain\Order\OrderId;
use App\Domain\Order\OrderRepository;
use App\Domain\Order\TaxPolicy;
use App\Domain\Customer\CustomerId;
use App\Domain\Customer\CustomerRepository;

final class PlaceOrder
{
    public function __construct(
        private OrderRepository $orders,
        private CustomerRepository $customers,
        private TaxPolicy $tax,
        private IdGenerator $ids,
    ) {}

    public function __invoke(PlaceOrderInput $in): PlaceOrderOutput
    {
        $customer = $this->customers->find(
            new CustomerId($in->customerId),
        );
        if ($customer === null || ! $customer->isActive()) {
            throw new CustomerNotEligible($in->customerId);
        }

        $order = Order::place(
            new OrderId($this->ids->next()),
            $customer->id(),
            $in->lineItems(),
            $this->tax,
        );

        $this->orders->save($order);

        return PlaceOrderOutput::from($order);
    }
}

Enter fullscreen mode Exit fullscreen mode

The use case has one job: make a decision and persist its consequence. HTTP, a queue, a console command — any of them can call it without the use case learning where the call came from.

The controller is an adapter (yes, still)

Now the controller. It still uses AbstractController if you want the conveniences. That is fine. What it is not allowed to do is hold business policy.

namespace App\Infrastructure\Http;

use App\Application\Order\PlaceOrder;
use App\Application\Order\PlaceOrderInput;
use App\Application\Order\CustomerNotEligible;
use App\Domain\Order\EmptyCartException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;

final class OrderController extends AbstractController
{
    public function __construct(private PlaceOrder $placeOrder) {}

    #[Route('/orders', methods: ['POST'])]
    public function create(Request $request): JsonResponse
    {
        try {
            $output = ($this->placeOrder)(
                PlaceOrderInput::fromJson($request->getContent()),
            );
        } catch (CustomerNotEligible | EmptyCartException $e) {
            return new JsonResponse(
                ['error' => $e->getMessage()],
                422,
            );
        }

        return new JsonResponse(
            ['id' => $output->orderId, 'total' => $output->totalEuros],
            201,
        );
    }
}

Enter fullscreen mode Exit fullscreen mode

Parse the request, call the use case, translate the result, translate the exception. No EntityManager, no OrderRepository, no OrderManager. The controller translates between HTTP and the application. That is the only job it has.

Notice the controller still extends AbstractController. Nothing in the hexagonal rulebook forbids that. The point isn't to avoid Symfony's helpers. The point is to keep Symfony out of the domain. The controller sits in Infrastructure/, where Symfony belongs.

Messenger transports are adapters too

The temptation with Messenger is to write the handler as if it were the application. Messenger gives you typed messages, attribute-registered handlers, transports, middleware. It is sophisticated enough that "just put the logic in the handler, it is async anyway" feels reasonable.

It is not. The handler is an adapter — same as the controller. Its job is to translate a message into a use-case call.

namespace App\Infrastructure\Messenger;

use App\Application\Order\PlaceOrder;
use App\Application\Order\PlaceOrderInput;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler]
final class PlaceOrderMessageHandler
{
    public function __construct(private PlaceOrder $placeOrder) {}

    public function __invoke(PlaceOrderMessage $message): void
    {
        ($this->placeOrder)(new PlaceOrderInput(
            customerId: $message->customerId,
            currency: $message->currency,
            items: $message->items,
        ));
    }
}

Enter fullscreen mode Exit fullscreen mode

Three lines of translation. The use case is the same class the HTTP controller calls. If you swap Messenger for a different transport, or move the work from sync to async behind a feature flag, the only file that changes is the handler. The use case never finds out.

Messenger's transports config is part of the same adapter ring:

# config/packages/messenger.yaml
framework:
    messenger:
        transports:
            async:
                dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
                retry_strategy:
                    max_retries: 3
                    multiplier: 2

        routing:
            App\Infrastructure\Messenger\PlaceOrderMessage: async

Enter fullscreen mode Exit fullscreen mode

That YAML is configuration of an adapter. It can change from Doctrine transport to AMQP to Redis without the domain noticing.

Messenger handler as adapter, same use case as HTTP

services.yaml is where the hexagon is wired

Symfony's DI container is one of the framework's strongest features. Autowiring with attributes does most of the work for free. The two places it cannot read your mind are: binding interface to implementation, and choosing between multiple implementations of the same interface.

# config/services.yaml
services:
    _defaults:
        autowire: true
        autoconfigure: true

    App\:
        resource: '../src/'
        exclude:
            - '../src/Domain/'
            - '../src/Kernel.php'

    App\Domain\Order\OrderRepository:
        alias: App\Infrastructure\Persistence\Doctrine\DoctrineOrderRepository

    App\Domain\Order\TaxPolicy:
        alias: App\Infrastructure\Tax\EuVatTaxPolicy

Enter fullscreen mode Exit fullscreen mode

The two alias lines are the dependency rule in YAML form. Every class in App\Application\* that asks for OrderRepository gets the Doctrine implementation. The application code never imports a Doctrine namespace.

The exclude: ../src/Domain/ line is the one teams forget. Domain classes are values, entities, aggregates — they are not services. Letting Symfony try to autowire Order is a category error. Exclude the directory and the container stays clean.

In tests, override the alias in config/services_test.yaml to point at an in-memory repository. The use-case tests run in milliseconds with no database.

Doctrine lifecycle hooks are not domain methods

The last thing to move out is the #[PrePersist] hook. It looked harmless in the legacy entity. It is not.

A #[PrePersist] tax calculation only runs when the EntityManager flushes. Unit-testing it requires an EntityManager. Running it twice in the same transaction produces surprises. A Messenger handler that places an order through the same code path either skips the conversion or runs a parallel one. The hook welds the tax rule to a persistence event.

The fix is mechanical. The pure Order becomes the only place tax math lives. The Doctrine entity (renamed OrderRecord) becomes a flat data carrier: columns and getters, no #[HasLifecycleCallbacks], no #[PrePersist]. The mapper between OrderRecord and Order lives in the Doctrine adapter, and it is the only file in the codebase that imports both namespaces.

namespace App\Infrastructure\Persistence\Doctrine;

final class DoctrineOrderRepository implements OrderRepository
{
    public function __construct(
        private EntityManagerInterface $em,
        private OrderMapper $mapper,
    ) {}

    public function find(OrderId $id): ?Order
    {
        $record = $this->em->find(OrderRecord::class, $id->value);
        if ($record === null) {
            return null;
        }
        $record->getItems()->initialize();
        return $this->mapper->toDomain($record);
    }

    public function save(Order $order): void
    {
        $record = $this->em->find(OrderRecord::class, $order->id->value)
            ?? new OrderRecord($order->id->value);

        $this->mapper->applyToRecord($order, $record);

        $this->em->persist($record);
        $this->em->flush();
    }
}

Enter fullscreen mode Exit fullscreen mode

The repository hands the use case a fully materialized Order with no proxies, no PersistentCollection, and no lazy traps. The initialize() call is explicit on purpose: the mapper is allowed to assume the items are loaded because the repository guarantees it.

What you keep, what you let Symfony do

Keep these in your code:

  • Domain/ with no Symfony imports and no Doctrine imports.
  • Ports (interfaces) defined in domain language, in Domain/.
  • Use cases in Application/ with constructor-injected ports.
  • One CI check that fails if Domain/ imports Symfony\ or Doctrine\.

Let Symfony do these — and stop pretending it shouldn't:

  • Routing, controller resolution, request parsing, response writing.
  • Messenger transports, retries, dead-letter routing.
  • The DI container, autowiring, services.yaml aliases.
  • Doctrine persistence, migrations, query building.
  • Validator, Mailer, HttpClient — used inside adapters, never inside the domain.

Symfony is a very capable adapter, and the more of it you let do its job, the less code you write. The mistake is letting Symfony into the part of the code that should outlive it.

If you want a place to start on Monday morning, pick the one entity in your codebase with a #[PrePersist] or #[PreUpdate] hook doing business math. Write the pure-PHP twin next to it, move the math, and let the Doctrine class shrink to columns and getters. That single refactor is the smallest version of the whole exercise, and the rest of the codebase will tell you where to go next.


If this was useful

This is the Symfony slice of a longer playbook. Decoupled PHP walks both Laravel and Symfony migrations end to end — full reference application, real refactor, the strangler year, the gotchas no Doctrine tutorial mentions. If your team has been arguing about where business logic should live and the answer keeps being "in the service layer," the book is what that argument looks like resolved.

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.