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

推荐订阅源

让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
小众软件
小众软件
V
Vulnerabilities – Threatpost
P
Proofpoint News Feed
The Register - Security
The Register - Security
A
About on SuperTechFans
L
LINUX DO - 热门话题
Blog — PlanetScale
Blog — PlanetScale
V
Visual Studio Blog
The Cloudflare Blog
The Last Watchdog
The Last Watchdog
Google DeepMind News
Google DeepMind News
L
LangChain Blog
博客园_首页
M
MIT News - Artificial intelligence
C
CERT Recently Published Vulnerability Notes
Recent Announcements
Recent Announcements
NISL@THU
NISL@THU
P
Privacy & Cybersecurity Law Blog
MongoDB | Blog
MongoDB | Blog
C
Check Point Blog
C
Cybersecurity and Infrastructure Security Agency CISA
G
GRAHAM CLULEY
Scott Helme
Scott Helme
P
Palo Alto Networks Blog
博客园 - Franky
The Hacker News
The Hacker News
Microsoft Security Blog
Microsoft Security Blog
爱范儿
爱范儿
Security Latest
Security Latest
腾讯CDC
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Threat Research - Cisco Blogs
Know Your Adversary
Know Your Adversary
P
Proofpoint News Feed
T
The Exploit Database - CXSecurity.com
T
Tenable Blog
V
V2EX
Hacker News: Ask HN
Hacker News: Ask HN
大猫的无限游戏
大猫的无限游戏
MyScale Blog
MyScale Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
S
SegmentFault 最新的问题
Latest news
Latest news
S
Schneier on Security
博客园 - 三生石上(FineUI控件)
L
Lohrmann on Cybersecurity
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
T
Tor Project blog
Application and Cybersecurity Blog
Application and Cybersecurity 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
Query Objects in PHP: Rich Filtering Without Leaking SQL Into the Domain
Gabriel Anhaia · 2026-06-14 · via DEV Community

You ship a list endpoint. GET /orders. It returns the customer's orders, newest first. Clean.

Then product wants a status filter. Then a date range. Then "only orders over 100 euros". Then pagination. Then sort by total, descending. Six months later the controller signature reads like a tax form, and the repository method that backs it is findByCustomerAndStatusAndMinTotalBetweenDatesOrderedBy(...) with nine parameters, three of them nullable.

So you "fix" it. You let the caller pass a Doctrine QueryBuilder into the repository. Or worse: the use case starts assembling WHERE clauses as strings because that was the fastest way to add the next filter on a Friday. Now your application layer knows about table aliases and SQL operators. The domain speaks SQL, and the whole point of having a repository interface is gone.

There is a shape that holds: a query object the domain builds, and an adapter that translates it into SQL. The caller describes what it wants in domain terms. The adapter decides how to fetch it.

The leak, concretely

Here is the version that grows out of control. Every new filter is another nullable parameter.

public function search(
    ?string $customerId,
    ?string $status,
    ?DateTimeImmutable $from,
    ?DateTimeImmutable $to,
    ?int $minTotalCents,
    string $sortBy = 'placedAt',
    string $direction = 'DESC',
    int $page = 1,
    int $perPage = 20,
): array;

Nine parameters, half of them nullable, two of them (sortBy, direction) carrying raw column names that map straight to SQL. Add a filter and the signature grows again. Every caller has to remember positional order. And $sortBy is a column name leaking through the port: the day you rename the column, every call site breaks.

The instinct to hand a QueryBuilder across the boundary is worse. The use case ends up importing Doctrine\ORM\QueryBuilder, which means the application layer now depends on the ORM. You cannot test it without a database, and you cannot swap the storage backend without rewriting business code.

A Criteria object the domain owns

Move the filters into a value object that lives in the application layer and speaks domain language. No column names. No SQL operators. Just fields the business understands.

<?php

declare(strict_types=1);

namespace App\Application\Order;

use App\Domain\Customer\CustomerId;
use App\Domain\Order\OrderStatus;
use DateTimeImmutable;

final class OrderCriteria
{
    /** @var OrderStatus[] */
    public array $statuses = [];
    public ?CustomerId $customerId = null;
    public ?DateTimeImmutable $placedAfter = null;
    public ?DateTimeImmutable $placedBefore = null;
    public ?int $minTotalCents = null;

    public OrderSort $sort = OrderSort::PlacedAtDesc;
    public int $page = 1;
    public int $perPage = 20;

    public function forCustomer(CustomerId $id): self
    {
        $clone = clone $this;
        $clone->customerId = $id;
        return $clone;
    }

    public function withStatus(
        OrderStatus $first,
        OrderStatus ...$rest,
    ): self {
        $clone = clone $this;
        $clone->statuses = [$first, ...$rest];
        return $clone;
    }

    public function placedBetween(
        DateTimeImmutable $after,
        DateTimeImmutable $before,
    ): self {
        $clone = clone $this;
        $clone->placedAfter = $after;
        $clone->placedBefore = $before;
        return $clone;
    }

    public function minTotal(int $cents): self
    {
        $clone = clone $this;
        $clone->minTotalCents = $cents;
        return $clone;
    }

    public function sortedBy(OrderSort $sort): self
    {
        $clone = clone $this;
        $clone->sort = $sort;
        return $clone;
    }

    public function paginate(int $page, int $perPage): self
    {
        $clone = clone $this;
        $clone->page = $page;
        $clone->perPage = $perPage;
        return $clone;
    }
}

OrderSort is an enum, not a string. The caller picks from a closed set, so there is no way to pass a column name that does not exist.

<?php

declare(strict_types=1);

namespace App\Application\Order;

enum OrderSort
{
    case PlacedAtDesc;
    case PlacedAtAsc;
    case TotalDesc;
    case TotalAsc;
}

Every builder method returns a clone, including the ones for sort and pagination, so an OrderCriteria is effectively immutable once handed off: each adjustment yields a new object instead of changing the one the repository already holds. You read a call site and the intent is plain:

$criteria = (new OrderCriteria())
    ->forCustomer($customerId)
    ->withStatus(OrderStatus::Placed, OrderStatus::Shipped)
    ->minTotal(10_000);

No SQL. No table aliases. A reader who has never touched the database understands exactly what is being asked.

The port stays thin

The repository interface gains one method and loses the parameter pile.

<?php

declare(strict_types=1);

namespace App\Application\Port;

use App\Application\Order\OrderCriteria;
use App\Domain\Order\Order;

interface OrderRepository
{
    public function save(Order $order): void;

    /** @return Order[] */
    public function matching(OrderCriteria $criteria): array;

    public function countMatching(OrderCriteria $criteria): int;
}

matching takes one argument. Add a filter next quarter and the signature does not change; you add a field to OrderCriteria and teach the adapter to read it. The port is stable. That stability is the whole payoff.

The adapter does the translation

This is the only file that knows SQL exists. It reads the criteria fields and assembles a query. Doctrine's QueryBuilder with parameter binding keeps it injection-safe.

<?php

declare(strict_types=1);

namespace App\Infrastructure\Persistence\Doctrine;

use App\Application\Order\OrderCriteria;
use App\Application\Order\OrderSort;
use App\Application\Order\OrderRepository;
use App\Domain\Order\Order;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\QueryBuilder;

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

    /** @return Order[] */
    public function matching(OrderCriteria $c): array
    {
        $qb = $this->applyFilters($c);
        $this->applySort($qb, $c->sort);

        $qb->setFirstResult(($c->page - 1) * $c->perPage)
           ->setMaxResults($c->perPage);

        $records = $qb->getQuery()->getResult();

        return array_map(
            fn ($r) => $this->mapper->toDomain($r),
            $records,
        );
    }

    public function countMatching(OrderCriteria $c): int
    {
        $qb = $this->applyFilters($c);
        $qb->select('COUNT(o.id)');

        return (int) $qb->getQuery()->getSingleScalarResult();
    }

    private function applyFilters(OrderCriteria $c): QueryBuilder
    {
        $qb = $this->em->createQueryBuilder()
            ->select('o')
            ->from(OrderRecord::class, 'o');

        if ($c->customerId !== null) {
            $qb->andWhere('o.customerId = :cid')
               ->setParameter('cid', $c->customerId->value);
        }

        if ($c->statuses !== []) {
            $names = array_map(
                fn ($s) => $s->value,
                $c->statuses,
            );
            $qb->andWhere('o.status IN (:statuses)')
               ->setParameter('statuses', $names);
        }

        if ($c->placedAfter !== null) {
            $qb->andWhere('o.placedAt >= :after')
               ->setParameter('after', $c->placedAfter);
        }

        if ($c->placedBefore !== null) {
            $qb->andWhere('o.placedAt <= :before')
               ->setParameter('before', $c->placedBefore);
        }

        if ($c->minTotalCents !== null) {
            $qb->andWhere('o.totalCents >= :minTotal')
               ->setParameter('minTotal', $c->minTotalCents);
        }

        return $qb;
    }

    private function applySort(
        QueryBuilder $qb,
        OrderSort $sort,
    ): void {
        match ($sort) {
            OrderSort::PlacedAtDesc =>
                $qb->orderBy('o.placedAt', 'DESC'),
            OrderSort::PlacedAtAsc =>
                $qb->orderBy('o.placedAt', 'ASC'),
            OrderSort::TotalDesc =>
                $qb->orderBy('o.totalCents', 'DESC'),
            OrderSort::TotalAsc =>
                $qb->orderBy('o.totalCents', 'ASC'),
        };
    }
}

Two things to notice. The match on OrderSort is the only place column names appear, and it is exhaustive: add a case to the enum and PHPStan flags the unhandled branch. There is no path from a request string to an ORDER BY clause, so the classic sort-injection hole is closed by construction.

Second, countMatching reuses applyFilters. The count query and the page query share one filter assembly, so they can never drift. A bug where the count says 40 results but page 2 is empty because the filters diverged is impossible here.

The use case reads like prose

The application service that backs the endpoint translates the HTTP request into a criteria and calls the port. It never touches SQL.

<?php

declare(strict_types=1);

namespace App\Application\Order;

use App\Application\Port\OrderRepository;
use App\Domain\Customer\CustomerId;

final readonly class ListOrders
{
    public function __construct(
        private OrderRepository $orders,
    ) {}

    public function execute(ListOrdersInput $in): ListOrdersOutput
    {
        $criteria = (new OrderCriteria())
            ->forCustomer(new CustomerId($in->customerId));

        if ($in->statuses !== []) {
            $criteria = $criteria->withStatus(
                ...$in->toStatusEnums()
            );
        }

        if ($in->minTotalCents !== null) {
            $criteria = $criteria->minTotal($in->minTotalCents);
        }

        $criteria = $criteria->paginate(
            $in->page,
            min($in->perPage, 100),
        );

        $orders = $this->orders->matching($criteria);
        $total = $this->orders->countMatching($criteria);

        return new ListOrdersOutput($orders, $total, $in->page);
    }
}

The min($in->perPage, 100) cap is a business rule, so it lives in the use case, not the adapter. The adapter trusts the criteria it gets. The HTTP layer maps query params into ListOrdersInput and back out; it knows nothing about the storage.

What you get for the trouble

A test for the use case needs no database. An in-memory repository that filters an array against the same OrderCriteria fields satisfies the port, and the unit suite runs in milliseconds:

public function it_filters_by_status(): void
{
    $repo = new InMemoryOrderRepository([
        $placed, $shipped, $cancelled,
    ]);

    $result = $repo->matching(
        (new OrderCriteria())->withStatus(OrderStatus::Placed)
    );

    self::assertCount(1, $result);
}

If you run both InMemoryOrderRepository and DoctrineOrderRepository against the same contract test, you prove they read the criteria the same way. The fake stays honest.

The criteria object also gives you one place to add cross-cutting filters. Multi-tenancy is the common one: every query for a tenant must scope to that tenant. Set tenantId once in a decorator that wraps the repository, and no use case can forget it. That is far safer than hoping every author of every list endpoint remembers to add AND tenant_id = ?.

There is a cost. You write more files up front, and a trivial CRUD app does not need any of this. The query object earns its place when a list endpoint has more than two or three filters, when you have more than one storage backend (read replica, cache, search index), or when the same filter logic gets reused across endpoints. Below that bar, the nine-parameter method is fine.

The signal to reach for it is the one in the opening: the moment your domain or application code starts holding SQL fragments, table aliases, or column names. That is the leak. A criteria object plus a translating adapter seals it without giving up rich filtering.


If this was useful

The query-object pattern is one slice of the wider discipline in Decoupled PHP: keep the framework and the database on the outside, and keep the domain readable after the third ORM upgrade. The book works through ports, adapters, and the read-side patterns — criteria objects, read models, projections — that keep list endpoints from rotting into SQL soup.

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.