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

推荐订阅源

MongoDB | Blog
MongoDB | Blog
V
V2EX
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
有赞技术团队
有赞技术团队
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
罗磊的独立博客
月光博客
月光博客
爱范儿
爱范儿
D
Docker
U
Unit 42
P
Proofpoint News Feed
I
InfoQ
腾讯CDC
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
L
LangChain Blog
V
Visual Studio Blog
IT之家
IT之家
Vercel News
Vercel News
G
Google Developers Blog
M
MIT News - Artificial intelligence
美团技术团队
The GitHub Blog
The GitHub Blog
阮一峰的网络日志
阮一峰的网络日志
MyScale Blog
MyScale 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
Query Objects in PHP: Rich Filtering Without Leaking SQL ...
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.