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

推荐订阅源

大猫的无限游戏
大猫的无限游戏
S
SegmentFault 最新的问题
量子位
A
Arctic Wolf
L
Lohrmann on Cybersecurity
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
WordPress大学
WordPress大学
V
Vulnerabilities – Threatpost
博客园 - Franky
C
Cyber Attacks, Cyber Crime and Cyber Security
The Cloudflare Blog
Last Week in AI
Last Week in AI
The Hacker News
The Hacker News
I
Intezer
J
Java Code Geeks
P
Privacy International News Feed
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
S
Secure Thoughts
Cisco Talos Blog
Cisco Talos Blog
阮一峰的网络日志
阮一峰的网络日志
S
Securelist
Security Latest
Security Latest
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
小众软件
小众软件
Jina AI
Jina AI
有赞技术团队
有赞技术团队
人人都是产品经理
人人都是产品经理
博客园_首页
酷 壳 – CoolShell
酷 壳 – CoolShell
T
The Exploit Database - CXSecurity.com
雷峰网
雷峰网
T
Tenable Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
P
Privacy & Cybersecurity Law Blog
Simon Willison's Weblog
Simon Willison's Weblog
博客园 - 【当耐特】
T
Threat Research - Cisco Blogs
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
MongoDB | Blog
MongoDB | Blog
D
DataBreaches.Net
N
News | PayPal Newsroom
Google Online Security Blog
Google Online Security Blog
K
Kaspersky official blog
H
Help Net Security
宝玉的分享
宝玉的分享
罗磊的独立博客
Webroot Blog
Webroot Blog
月光博客
月光博客
B
Blog RSS Feed
Recorded Future
Recorded Future

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
Application Services vs Use Cases: The Actual Difference
Gabriel Anha · 2026-05-20 · via DEV Community

Two PHP engineers are reviewing a pull request. One says "this should be an application service." The other says "no, a use case." They argue for fifteen minutes, agree they mean the same thing, merge the PR, and the next sprint someone opens app/Services/OrderService.php and finds nineteen public methods, two private helpers, and four injected dependencies that only two of those methods actually use.

That argument repeats in every PHP codebase that imports clean or hexagonal vocabulary without locking down what the words mean. The terms are not interchangeable. They describe two different things at two different sizes. Once a team agrees on the distinction, "where does this code go" stops being a debate.

Here is the rule that ends it: an ApplicationService is a layer that holds related operations. A UseCase is a single operation: one verb, one class, one public method. Both are valid. Picking one is a project-wide decision, not a per-feature one.

What the two words actually point at

Eric Evans introduced application services in Domain-Driven Design (2003) as the thin orchestration layer that sits between the inbound side (controllers, CLI, queue workers) and the domain. Robert Martin used use cases in Clean Architecture (2017) for the same orchestration responsibility, but framed each one as its own object. Both authors agree on what the code does. They disagree on how to package it.

In a PHP codebase the difference shows up at the file level.

An ApplicationService groups verbs that share a noun:

final class OrderApplicationService
{
    public function __construct(
        private readonly OrderRepository $orders,
        private readonly PaymentGateway $payments,
        private readonly EventDispatcher $events,
        private readonly Clock $clock,
    ) {}

    public function create(CreateOrderCommand $cmd): OrderId { /* ... */ }
    public function cancel(CancelOrderCommand $cmd): void    { /* ... */ }
    public function refund(RefundOrderCommand $cmd): void    { /* ... */ }
}

Enter fullscreen mode Exit fullscreen mode

A UseCase isolates one verb in its own class:

final class CreateOrderUseCase
{
    public function __construct(
        private readonly OrderRepository $orders,
        private readonly Clock $clock,
    ) {}

    public function execute(CreateOrderCommand $cmd): OrderId { /* ... */ }
}

Enter fullscreen mode Exit fullscreen mode

The orchestration, dependency set, and domain boundary are identical. Only the packaging changes. That is the whole disagreement.

ApplicationService as one wide box holding multiple verbs versus a row of single-verb UseCase stamps

The worked example: three verbs, two packagings

Here is the same order feature written both ways, in PHP 8.3, against the same domain. The domain types and ports are constant across both versions; only the application layer changes.

Shared pieces first.

<?php
declare(strict_types=1);

namespace App\Domain\Order;

final readonly class OrderId
{
    public function __construct(public string $value) {}
}

final class Order
{
    public function __construct(
        public readonly OrderId $id,
        public readonly string $customerId,
        public readonly int $totalCents,
        public readonly \DateTimeImmutable $createdAt,
        private string $status,
    ) {}

    public function cancel(): void
    {
        if ($this->status !== 'pending') {
            throw new \DomainException(
                "cannot cancel order in status {$this->status}"
            );
        }
        $this->status = 'cancelled';
    }

    public function refund(): void
    {
        if ($this->status !== 'paid') {
            throw new \DomainException(
                "cannot refund order in status {$this->status}"
            );
        }
        $this->status = 'refunded';
    }

    public function status(): string
    {
        return $this->status;
    }
}

Enter fullscreen mode Exit fullscreen mode

Two ports, one for persistence and one for the payment side.

<?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 get(OrderId $id): Order;
}

interface PaymentGateway
{
    public function refund(OrderId $id, int $amountCents): void;
}

Enter fullscreen mode Exit fullscreen mode

Three commands, one per verb.

<?php
declare(strict_types=1);

namespace App\Application\Command;

final readonly class CreateOrderCommand
{
    public function __construct(
        public string $customerId,
        public int $totalCents,
    ) {}
}

final readonly class CancelOrderCommand
{
    public function __construct(public string $orderId) {}
}

final readonly class RefundOrderCommand
{
    public function __construct(public string $orderId) {}
}

Enter fullscreen mode Exit fullscreen mode

Version A — one ApplicationService class with three verbs

<?php
declare(strict_types=1);

namespace App\Application\Service;

use App\Application\Command\CancelOrderCommand;
use App\Application\Command\CreateOrderCommand;
use App\Application\Command\RefundOrderCommand;
use App\Application\Port\OrderRepository;
use App\Application\Port\PaymentGateway;
use App\Domain\Clock;
use App\Domain\Order\Order;
use App\Domain\Order\OrderId;

final class OrderApplicationService
{
    public function __construct(
        private readonly OrderRepository $orders,
        private readonly PaymentGateway $payments,
        private readonly Clock $clock,
    ) {}

    public function create(CreateOrderCommand $cmd): OrderId
    {
        $order = new Order(
            id:         new OrderId(bin2hex(random_bytes(8))),
            customerId: $cmd->customerId,
            totalCents: $cmd->totalCents,
            createdAt:  $this->clock->now(),
            status:     'pending',
        );
        $this->orders->save($order);
        return $order->id;
    }

    public function cancel(CancelOrderCommand $cmd): void
    {
        $order = $this->orders->get(new OrderId($cmd->orderId));
        $order->cancel();
        $this->orders->save($order);
    }

    public function refund(RefundOrderCommand $cmd): void
    {
        $order = $this->orders->get(new OrderId($cmd->orderId));
        $order->refund();
        $this->payments->refund($order->id, $order->totalCents);
        $this->orders->save($order);
    }
}

Enter fullscreen mode Exit fullscreen mode

Notice what this version pays: every method has access to every constructor dependency, whether it needs it or not. create and cancel never touch $this->payments, but it is wired in regardless. That is the trade-off: convenience of grouping in exchange for looser dependency hygiene.

Version B — three UseCase classes, one verb each

<?php
declare(strict_types=1);

namespace App\Application\UseCase;

use App\Application\Command\CreateOrderCommand;
use App\Application\Port\OrderRepository;
use App\Domain\Clock;
use App\Domain\Order\Order;
use App\Domain\Order\OrderId;

final class CreateOrderUseCase
{
    public function __construct(
        private readonly OrderRepository $orders,
        private readonly Clock $clock,
    ) {}

    public function execute(CreateOrderCommand $cmd): OrderId
    {
        $order = new Order(
            id:         new OrderId(bin2hex(random_bytes(8))),
            customerId: $cmd->customerId,
            totalCents: $cmd->totalCents,
            createdAt:  $this->clock->now(),
            status:     'pending',
        );
        $this->orders->save($order);
        return $order->id;
    }
}

Enter fullscreen mode Exit fullscreen mode

<?php
declare(strict_types=1);

namespace App\Application\UseCase;

use App\Application\Command\CancelOrderCommand;
use App\Application\Port\OrderRepository;
use App\Domain\Order\OrderId;

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

    public function execute(CancelOrderCommand $cmd): void
    {
        $order = $this->orders->get(new OrderId($cmd->orderId));
        $order->cancel();
        $this->orders->save($order);
    }
}

Enter fullscreen mode Exit fullscreen mode

<?php
declare(strict_types=1);

namespace App\Application\UseCase;

use App\Application\Command\RefundOrderCommand;
use App\Application\Port\OrderRepository;
use App\Application\Port\PaymentGateway;
use App\Domain\Order\OrderId;

final class RefundOrderUseCase
{
    public function __construct(
        private readonly OrderRepository $orders,
        private readonly PaymentGateway $payments,
    ) {}

    public function execute(RefundOrderCommand $cmd): void
    {
        $order = $this->orders->get(new OrderId($cmd->orderId));
        $order->refund();
        $this->payments->refund($order->id, $order->totalCents);
        $this->orders->save($order);
    }
}

Enter fullscreen mode Exit fullscreen mode

Three files instead of one. Each class names exactly what it needs. CancelOrderUseCase has no idea PaymentGateway exists; CreateOrderUseCase does not pull in either of the other dependencies. The signature of each constructor is a precise inventory of the verb.

Side-by-side: what each style costs and pays for

Table-style comparison of grouping by noun versus splitting by verb, with check and cross marks against six properties

Property ApplicationService (layer) UseCase (per verb)
File count 1 per noun N per noun
Constructor scope Union of all verbs' deps Exactly this verb's deps
Where readers look first The class The folder listing
Testing setup Mock everything per test Mock only what this verb needs
Refactoring a single verb Touches a shared class Touches one isolated class
New verb on the same noun Add a method Add a file
Container wiring One binding per noun One binding per verb
Risk of God-class drift Real, watch for it Structurally hard
Risk of folder bloat Low Real at 50+ verbs
CQRS / handler buses fit Awkward (1-to-many) Native (1-to-1)

Neither column is wrong. The right column is what Robert Martin draws on the whiteboard; the left column is what most Laravel and Symfony tutorials write. Teams get into trouble when half the codebase is one and half is the other.

How to pick one and stop arguing

Use ApplicationService when:

  • The team is small and the surface area is small. Three to six verbs per noun, no plans to grow much.
  • You are not running a command bus or a CQRS-style handler discovery. The orchestration entry point is the controller, and one injected service per noun is easier to wire than ten.
  • The verbs share a lot of state-validation logic and pulling it into private methods on the same class is cleaner than extracting a shared collaborator.
  • The team is new to clean/hexagonal vocabulary and you want a forgiving starting layer that won't explode into hundreds of files in week two.

Use UseCase when:

  • The team uses a command bus (Symfony Messenger, Tactician, a homemade one) and each command needs a single handler. The 1-to-1 mapping is exactly what these libraries expect.
  • Constructor hygiene matters more than file count. Reviewers should see at a glance which ports a single operation touches.
  • The codebase has fifty or more verbs across a few nouns and the would-be OrderApplicationService is heading toward a thousand-line file with thirty dependencies.
  • You want a one-screen unit of work that can be reasoned about, tested, and replaced in isolation.

The team makes one of those calls, writes it into the project's architecture doc, and stops debating it per-PR.

Two anti-patterns that ruin both styles

The God service. An OrderApplicationService with twenty-two public methods, fourteen injected dependencies, and a private function ensureOrderIsValid() that two-thirds of the methods call. This is the version everyone has met, and it is the reason people write angry blog posts about service layers. Renaming to UseCase changes nothing. The fix is to split the noun (OrderLifecycle, OrderRefunds, OrderFulfilment) or go per-verb.

The shadow service. A folder of UseCase classes where every class extends a BaseUseCase that injects a ServiceContainer and pulls dependencies out of it. The constructor lists nothing; the body calls $this->container->get(OrderRepository::class). This is an ApplicationService wearing a UseCase costume. It defeats the whole point: the constructor no longer tells you what the verb needs, and tests have to stub a container instead of passing two arguments. If the team picks UseCase, the constructor lists the real ports. Otherwise, pick ApplicationService and stop pretending.

Both anti-patterns come from the same place: treating the naming choice as decoration instead of a structural commitment. The structural commitment is what matters.

What survives across both styles

Whatever you pick, the rules below hold:

  • The application layer never imports from the framework. No Eloquent models, no Symfony attributes, no Laravel facades. The application orchestrates the domain through ports.
  • The domain knows nothing about the application layer. Entities and value objects sit one ring further in and stay there.
  • One command class per verb, no matter whether the verb lives in its own UseCase or as a method on an ApplicationService. The command is the contract; the handler is the implementation.
  • Controllers and CLI commands and queue workers are inbound adapters. They translate transport-level input into a command and call the application. They do not contain business logic.
  • Ports live with the application layer (or the domain), not with the adapters that implement them. The application names the shape of what it needs; infrastructure conforms.

If those five rules hold, you can swap an OrderApplicationService for three UseCase classes in an afternoon without touching the domain, the controllers, or the tests beyond their setup blocks. The two styles are swap-compatible inside the same architecture. They are not swap-compatible in everyday code review. That is the conversation worth having on your team this week.


If this was useful

The "where does this code go" question is half of what makes hexagonal and clean architecture feel hard in PHP, and naming conventions are the other half. Decoupled PHP walks the full project shape (domain, ports, application, adapters) with both architectures side by side, in PHP 8.3, with a public examples repo for each chapter. If your team has been arguing about service-versus-use-case for longer than is healthy, the book picks a side and shows the trade.

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.