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

推荐订阅源

S
Schneier on Security
C
Cyber Attacks, Cyber Crime and Cyber Security
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Project Zero
Project Zero
T
The Exploit Database - CXSecurity.com
G
GRAHAM CLULEY
T
Threatpost
A
Arctic Wolf
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Scott Helme
Scott Helme
Simon Willison's Weblog
Simon Willison's Weblog
P
Proofpoint News Feed
C
Cisco Blogs
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
K
Kaspersky official blog
P
Palo Alto Networks Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
T
Threat Research - Cisco Blogs
The Hacker News
The Hacker News
T
Tor Project blog
NISL@THU
NISL@THU
The GitHub Blog
The GitHub Blog
Security Latest
Security Latest
aimingoo的专栏
aimingoo的专栏
C
CERT Recently Published Vulnerability Notes
Recorded Future
Recorded Future
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Google DeepMind News
Google DeepMind News
Martin Fowler
Martin Fowler
N
News | PayPal Newsroom
P
Privacy & Cybersecurity Law Blog
MyScale Blog
MyScale Blog
G
Google Developers Blog
V
V2EX
V
Visual Studio Blog
P
Privacy International News Feed
Google Online Security Blog
Google Online Security Blog
Microsoft Azure Blog
Microsoft Azure Blog
宝玉的分享
宝玉的分享
博客园 - 【当耐特】
L
LINUX DO - 热门话题
MongoDB | Blog
MongoDB | Blog
腾讯CDC
J
Java Code Geeks
The Last Watchdog
The Last Watchdog
L
Lohrmann on Cybersecurity
Cyberwarzone
Cyberwarzone
博客园 - 聂微东
Webroot Blog
Webroot Blog
S
Secure Thoughts

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
Persisting One Aggregate Across Multiple Tables, ORM-Agnostic
Gabriel Anhaia · 2026-06-14 · via DEV Community

You have an Order. It owns line items and a shipping address. In the
database that is three tables: orders, order_items,
order_addresses. The aggregate is one thing in the domain and three
rows-with-children in storage.

Now look at what most codebases do with that. The service loads the
order, loops the items, saves each one in its own statement. Halfway
through, a unique-constraint violation throws. The order header is
already committed. Two items are in. One address is missing. You have a
row in orders that no part of the system considers valid, and no
single place to point at when you ask how it got there.

The aggregate is supposed to be a consistency boundary. Saving its
parts in separate, independently-committing operations breaks that
boundary on the way to disk. This post is about closing it: one
repository, one transactional save across every table, and a read path
that rebuilds the whole object from rows without leaking the ORM into
the domain.

The aggregate the domain sees

The domain class has no idea it lives in three tables. It holds its
children directly and guards their invariants.

<?php

declare(strict_types=1);

namespace App\Domain\Order;

use App\Domain\Shared\Money;

final class Order
{
    /** @var list<LineItem> */
    private array $items;

    private function __construct(
        private readonly OrderId $id,
        private readonly CustomerId $customerId,
        array $items,
        private Address $shipTo,
        private OrderStatus $status,
    ) {
        if ($items === []) {
            throw new InvalidOrder('order needs an item');
        }
        $this->items = array_values($items);
    }

    public static function place(
        OrderId $id,
        CustomerId $customerId,
        array $items,
        Address $shipTo,
    ): self {
        return new self(
            $id, $customerId, $items,
            $shipTo, OrderStatus::Placed,
        );
    }

    public static function restore(
        OrderId $id,
        CustomerId $customerId,
        array $items,
        Address $shipTo,
        OrderStatus $status,
    ): self {
        return new self(
            $id, $customerId, $items, $shipTo, $status,
        );
    }

    public function total(): Money
    {
        $sum = Money::zero($this->items[0]->price->currency);
        foreach ($this->items as $item) {
            $sum = $sum->plus($item->lineTotal());
        }
        return $sum;
    }

    public function id(): OrderId { return $this->id; }
    public function status(): OrderStatus { return $this->status; }
    /** @return list<LineItem> */
    public function items(): array { return $this->items; }
    public function shipTo(): Address { return $this->shipTo; }
    public function customerId(): CustomerId
    {
        return $this->customerId;
    }
}

LineItem and Address are small value objects in the same namespace.
The point: the items are loaded the moment the order is. There is no
proxy, no getItems() that fires a query on first access. A loaded
Order is fully present in memory or it does not exist yet.

The port the use case depends on

The use case asks for an OrderRepository. The interface speaks domain
types and hides every table.

<?php

declare(strict_types=1);

namespace App\Application\Port;

use App\Domain\Order\Order;
use App\Domain\Order\OrderId;

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

One save, one find. The caller never sees that "save" touches three
tables. It hands over the aggregate and trusts the repository to land
the whole thing or none of it.

The write path: one transaction, three tables

Here is the adapter against raw PDO. No ORM, so nothing is hidden. You
can see the transaction open, the delete-then-insert for children, and
the commit.

<?php

declare(strict_types=1);

namespace App\Infrastructure\Persistence\Pdo;

use App\Application\Port\OrderRepository;
use App\Domain\Order\Order;
use App\Domain\Order\OrderId;
use PDO;

final readonly class PdoOrderRepository implements
    OrderRepository
{
    public function __construct(private PDO $pdo) {}

    public function save(Order $order): void
    {
        $this->pdo->beginTransaction();
        try {
            $this->upsertHeader($order);
            $this->replaceItems($order);
            $this->replaceAddress($order);
            $this->pdo->commit();
        } catch (\Throwable $e) {
            $this->pdo->rollBack();
            throw $e;
        }
    }

    private function upsertHeader(Order $order): void
    {
        $sql = 'INSERT INTO orders
                  (id, customer_id, status)
                VALUES (:id, :cust, :status)
                ON DUPLICATE KEY UPDATE
                  status = VALUES(status)';
        $this->pdo->prepare($sql)->execute([
            'id' => $order->id()->value,
            'cust' => $order->customerId()->value,
            'status' => $order->status()->value,
        ]);
    }

    private function replaceItems(Order $order): void
    {
        $del = $this->pdo->prepare(
            'DELETE FROM order_items WHERE order_id = :id'
        );
        $del->execute(['id' => $order->id()->value]);

        $ins = $this->pdo->prepare(
            'INSERT INTO order_items
               (order_id, sku, qty, price_minor, currency)
             VALUES (:oid, :sku, :qty, :price, :cur)'
        );
        foreach ($order->items() as $item) {
            $ins->execute([
                'oid' => $order->id()->value,
                'sku' => $item->sku,
                'qty' => $item->quantity,
                'price' => $item->price->amountMinor,
                'cur' => $item->price->currency,
            ]);
        }
    }

    private function replaceAddress(Order $order): void
    {
        $a = $order->shipTo();
        $sql = 'INSERT INTO order_addresses
                  (order_id, line1, city, country)
                VALUES (:id, :l1, :city, :country)
                ON DUPLICATE KEY UPDATE
                  line1 = VALUES(line1),
                  city = VALUES(city),
                  country = VALUES(country)';
        $this->pdo->prepare($sql)->execute([
            'id' => $order->id()->value,
            'l1' => $a->line1,
            'city' => $a->city,
            'country' => $a->country,
        ]);
    }
}

Three things earn their place here.

The whole write is in one transaction. If the address insert fails, the
header and items roll back with it. The database never holds a
half-written aggregate. That is the consistency boundary, honored at the
storage edge.

Children are replaced, not diffed. DELETE every order_item for this
order, then re-insert the current set. You skip the bookkeeping of
"which item is new, which changed, which was removed." The aggregate in
memory is the source of truth; the rows become a copy of it. For a
small child collection this is the simplest correct option, and it is
within one transaction, so no reader ever sees the gap between delete
and insert.

The header upsert means save works for both a new order and an edited
one. The use case calls save and does not branch on whether the order
existed.

The read path: rebuild the whole from rows

Loading is the mirror image. Pull every table for the id, then hand the
rows to a factory that rebuilds the aggregate.

public function findById(OrderId $id): ?Order
{
    $header = $this->fetchHeader($id->value);
    if ($header === null) {
        return null;
    }

    $items = $this->fetchItems($id->value);
    $address = $this->fetchAddress($id->value);

    return OrderMapper::toDomain($header, $items, $address);
}

private function fetchHeader(string $id): ?array
{
    $stmt = $this->pdo->prepare(
        'SELECT id, customer_id, status
         FROM orders WHERE id = :id'
    );
    $stmt->execute(['id' => $id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return $row === false ? null : $row;
}

private function fetchItems(string $id): array
{
    $stmt = $this->pdo->prepare(
        'SELECT sku, qty, price_minor, currency
         FROM order_items WHERE order_id = :id'
    );
    $stmt->execute(['id' => $id]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

Three queries, all eager. The order, its items, its address, fetched
before the aggregate is built. No state in the returned Order is a
promise to query later. That is the difference between this and a lazy
ORM relation, and it is the difference that bites in production.

A lazy collection looks loaded. You read $order->items() inside a
controller and it works, because the entity manager is still open. The
same call inside a queue worker, after the unit of work has closed,
throws a LazyInitializationException or hands you an empty set. The
read path above cannot do that. The items are plain value objects in an
array the moment findById returns.

The mapper keeps the ORM out of the domain

The mapper is the only code that knows column names. It turns rows into
value objects and calls the domain's restore factory.

<?php

declare(strict_types=1);

namespace App\Infrastructure\Persistence\Pdo;

use App\Domain\Order\Address;
use App\Domain\Order\CustomerId;
use App\Domain\Order\LineItem;
use App\Domain\Order\Order;
use App\Domain\Order\OrderId;
use App\Domain\Order\OrderStatus;
use App\Domain\Shared\Money;

final class OrderMapper
{
    public static function toDomain(
        array $header,
        array $itemRows,
        array $addressRow,
    ): Order {
        $items = array_map(
            static fn (array $r): LineItem => new LineItem(
                sku: $r['sku'],
                quantity: (int) $r['qty'],
                price: new Money(
                    (int) $r['price_minor'],
                    $r['currency'],
                ),
            ),
            $itemRows,
        );

        return Order::restore(
            id: new OrderId($header['id']),
            customerId: new CustomerId(
                $header['customer_id']
            ),
            items: $items,
            shipTo: new Address(
                $addressRow['line1'],
                $addressRow['city'],
                $addressRow['country'],
            ),
            status: OrderStatus::from($header['status']),
        );
    }
}

restore rebuilds the object without re-running placement invariants.
The rows were valid when they were written; re-checking them on load
hides the bug in whatever wrote a bad row. The domain Order has zero
imports from Infrastructure. Swap PDO for Doctrine's DBAL, or for a
document store that keeps the whole aggregate in one JSON column, and
only this adapter and mapper change.

Where the transaction actually lives

In the PDO adapter above, save owns its transaction, which is fine
when one save is one unit of work. The moment a use case saves two
aggregates that must commit together, the transaction belongs one layer
out, around the use case, behind a port:

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

The use case wraps its work in run(...); the repository's save joins
the open transaction instead of starting its own. The same delete-insert
write stays correct; it just stops being the outermost boundary. Either
way, the rule holds: the aggregate lands whole or not at all.

The discipline in one line

One aggregate maps to one repository. The repository owns the spread
across tables on write and the gather across tables on read. Children
load eagerly, save inside a single transaction, and the domain class
never learns a table name. That is the whole pattern, and it is the same
whether the ORM is Doctrine, Eloquent mapped to a side class, or raw
PDO.


If this was useful

This mapping problem — one aggregate, many tables, no leaks — gets a
full treatment in Decoupled PHP, next to the repository, transaction,
and unit-of-work patterns it leans on. The book's whole argument is that
storage is an adapter your domain shouldn't feel, and the order
aggregate here is the running example it builds on.

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.