Skip to content

Domain, Application & Infrastructure Services ​

"When a significant process or transformation in the domain is not a natural responsibility of an entity or value object, add an operation to the model as a standalone interface declared as a service." — Eric Evans, Domain-Driven Design Reference (2015), "Services"

Summary: "Service" names three different things in a DDD codebase: a domain service holds a business rule that belongs to no single entity, an application service runs one use case from start to finish without deciding anything, and an infrastructure service is a technical capability behind an interface the inside owns. Mixing them up is how business rules end up in controllers and SQL ends up in the model. Focus: The three kinds and their exact responsibilities, the dependency rule, ports and adapters, the composition root, command and query handlers (CQS), transactions and the unit of work, domain events dispatched after commit, cross-cutting concerns as decorators, DTOs and validation at the edge, the anti-patterns (fat application service, dumping-ground domain service, "Service" on everything, Eloquent or DB in the domain, static facades in the model), and the same PlaceOrder use case built end to end in Go and Laravel 13 with tests. Learning goal: Given any rule or line of code in an ordering system, say which of the three layers it belongs to and why. Write a thin use case that loads, decides through the domain, saves and publishes in one transaction. Put every external system behind a port the inside defines, and test each kind of service the cheapest way that still proves something.

This chapter is in group DD 02 (Tactical Design). It comes after Entities & Value Objects, Aggregates & Factories, Anemic vs Rich Domain Models and Repositories, and it uses all four. It owns one question: which code goes in which kind of service, and how do those services depend on each other? The neighbours own the rest. What a domain event is and how it differs from an integration event: Domain Events vs Integration Events. How the outbox relay publishes: Outbox Pattern. The layered, hexagonal, onion and clean styles compared as architectures: Layered Monolith. The principle underneath ports: Dependency Inversion Principle. How responsibilities are assigned to classes in general: Low-Level Design and Object-Oriented Modeling. How persistence is designed behind a repository port: Data Persistence Design. The running example is the online ordering and fulfilment business used across the DDD path. Its contexts are Sales, Fulfilment, Billing, Catalog and Identity, and the use case here is Sales' PlaceOrder.

Page map ​

If you are looking forGo to
The whole page in four tablesEverything in one minute
Why one word needs three meaningsWhy three kinds of service exist
Evans, Fowler/Stafford, Cockburn, Martin, Vernon, Three DotsWhere it comes from
Pricing across lines, tier and promotionsDomain service
Load, decide, save, publishApplication service / use case
Payment gateway, clock, email, storageInfrastructure service
Interfaces inside, implementations outsideDependency rule, ports and adapters
Commands change, queries answerCommand and query handlers
Where the transaction livesTransactions and the unit of work
Raise in the aggregate, dispatch after commitDomain events from the use case
Logging, metrics, auth, idempotencyCross-cutting concerns as decorators
Form Request, command DTO, result DTODTOs and validation at the edge
OrderService, OrderManager, OrderHelperNaming: the "Service" suffix
Request lifecycle, SQL, error codesMechanics
PlaceOrder end to end with testsGo, Laravel
Fat services, leaking Eloquent, facades in the modelSolving the classic problems
15 rules sorted into layersChoosing: where does this logic go?
Monolith to distributed dataIn architecture
Hands-onLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The three kinds. Every row is unpacked in the concept catalogue.

KindIn plain wordsExample in SalesHas state?Does I/O?Lives in
Domain serviceA business rule that belongs to no single entity or value objectPricingService.Quote(order, tier, promotions)NoNoDomain layer
Application service (use case, interactor, command handler)Runs one user goal: load, ask the domain, save, publishPlaceOrderHandler.Handle(PlaceOrder)No (only per-call progress)Only through portsApplication layer
Infrastructure serviceA technical capability the business does not care how you doStripePaymentGateway, SystemClock, SMTP mailerMay hold clients and poolsYes, that is the pointInfrastructure (adapters)

The dependency rule and its parts:

TermPlain wordsIn this chapter
Dependency ruleSource code points inward only; the domain imports nothing outside itselfsales imports no database/sql, no net/http, no Laravel facade
PortAn interface the inside owns, phrased in its own wordsOrderRepository, PaymentGateway, Clock, Outbox
AdapterAn implementation of a port with a specific technologypostgres.Orders, stripe.Gateway, EloquentOrderRepository
Driving (primary) adapterCalls into the applicationHTTP handler, Form Request + controller, queued job, CLI, test
Driven (secondary) adapterIs called by the applicationDatabase, payment provider, broker, clock
Composition rootThe one place that wires adapters into portscmd/shop/main.go, SalesServiceProvider

Command vs query at the application layer:

Command handlerQuery handler
PurposeChange state for one use caseReturn data for one screen or API
Loads an aggregate?Yes, through a repositoryNo, reads a view or table directly
TransactionYes, one per commandUsually none, or read-only
Raises eventsYes, via the aggregateNever
ReturnsNothing or a small result DTO (id, total)A DTO shaped for the reader
Scales withThe primary databaseReplicas, caches, projections (CQRS)

Anti-pattern → symptom → fix (detailed in Solving the classic problems):

Anti-patternSymptomFix
Fat application serviceif tier == "gold" inside PlaceOrderHandlerMove the rule into the aggregate or a domain service
Domain service as a dumping groundOrderDomainService with 40 unrelated methodsOne service per named operation; most go back to entities
"Service" suffix for everythingOrderService, OrderManager, OrderHelper side by sideName the operation in the ubiquitous language: PricingService, PlaceOrder
Infrastructure in the domainOrder::where(...), DB::table in a domain classRepository port in the domain, Eloquent in an adapter
Static facades in the modelCache::remember, now(), Mail:: inside OrderPass values in, or inject a port into the application service
External call inside the transactionStripe call between BEGIN and COMMITCall outside, compensate on failure, use an idempotency key
Events published before commitFulfilment ships an order that rolled backOutbox row in the same transaction, or ShouldDispatchAfterCommit

Why three kinds of service exist ​

The word "service" arrives in a codebase from at least three directions. Evans uses it for a domain operation with no natural home. Fowler's Patterns of Enterprise Application Architecture (chapter by Randy Stafford) uses Service Layer for the application boundary. Every framework uses it for "a class with a client in it": mail service, cache service, payment service. If the team does not separate the three, one class called OrderService ends up holding all three jobs. It decides the discount, opens the transaction, calls Stripe, writes SQL and formats the JSON. Nothing in it can be tested without a database and a network, and no rule in it can be reused from a queue worker or a CLI.

The split is by what kind of knowledge the code holds:

Separate the three kindsOne "service" does everything
A pricing rule is changed in one place and unit-tested in millisecondsThe rule is copied into the controller, the import job and the admin panel
The use case reads like the user story: load, place, save, publishThe use case is 200 lines of SQL, ifs and HTTP calls
Stripe can be swapped for Adyen by writing one adapterStripe's field names are spread across the domain
The same use case runs from HTTP, a queue, a CLI or a testEach entry point re-implements the flow
More files and interfaces up frontFewer files, until the second entry point appears
Good for: core domains with real rules (Domains & Subdomains)Acceptable for: generic CRUD where there are no rules to protect

The analogy we reuse on this page: a restaurant. The chef's judgement is the domain. The recipe, and the rule "this table gets the tasting-menu discount because it is a party of eight on a Tuesday", depend on several things at once and on nothing outside the kitchen. That judgement is a domain service. The expediter at the pass is the application service. They take the ticket, call the stations in order, check that the plate is complete, send it out and mark the ticket done. They cook nothing and decide no recipe. The card terminal, the supplier's delivery van and the dishwasher are infrastructure services. The restaurant needs them, but the menu does not change when the bank changes. The dependency rule says the recipe book never mentions the bank.

Infrastructure (adapters): technical capabilitiesApplication layer: use cases + portsDomain layerOrder aggregate, Money, QuotePricingService (domain service)OrderRepository (port)PaymentGatewayClockCatalogOutbox / UoWPlaceOrderHandlerStripe gatewaySystem clockCatalog readerPostgres UoWPostgres repoHTTP handlerQueue jobdatabase/sqlRule: every source-code arrow points inward. Interfaces live inside; implementations outside.forbidden

The picture shows the three rings. The domain sits in the centre with the Order aggregate, the PricingService domain service and the OrderRepository port it defines. The application layer holds the PlaceOrderHandler use case and the ports it needs: PaymentGateway, Clock, Catalog and Outbox. Infrastructure on the outside holds adapters: Stripe, the system clock, the Postgres repository, the HTTP handler and the queue job. Every source-code arrow points inward. The crossed-out arrow from the domain to database/sql is the one the dependency rule forbids.

Three common misunderstandings, up front ​

  1. "A domain service is where business logic goes when I use DDD." Most business logic belongs on entities and value objects. Evans's test is "not a natural responsibility of an entity or value object". A domain service is the exception, not the default. Moving rules out of entities into services produces the anemic domain model.
  2. "The application service is the business layer." Fowler, summarising Evans's layers, says the application layer "does not contain business rules or knowledge, but only coordinates tasks and delegates work to collaborations of domain objects in the next layer down." If you can delete the domain and the application service still computes prices, the rule is in the wrong place.
  3. "Infrastructure means the database." Infrastructure is any technical capability: payment providers, email, SMS, the clock, random and ID generation, file storage, feature flags, other services' APIs. The clock trips people most often. time.Now() or now() inside the domain is an infrastructure call.

Where it comes from ​

Fowler and Stafford, 2002–2003: Service Layer. Patterns of Enterprise Application Architecture has a chapter by Randy Stafford (the catalogue entry is dated 5 March 2003). It defines the pattern this way: "A Service Layer defines an application's boundary and its set of available operations from the perspective of interfacing client layers. It encapsulates the application's business logic, controlling transactions and coor-dinating responses in the implementation of its operations." That last sentence says the service layer encapsulates business logic. In DDD the same layer only coordinates and leaves the logic to the domain. The two traditions disagree on purpose: a PoEAA service layer may hold the logic itself, while a DDD application service must delegate it.

Evans, 2003: the three kinds named. Domain-Driven Design (Addison-Wesley, 2003) introduced the Services building block and the Layered Architecture pattern. The book separates application, domain and infrastructure services (we worked from the free DDD Reference, not the book). The Reference (2015) keeps the domain definition quoted at the top of this page and adds: "Define a service contract, a set of assertions about interactions with the service... State these assertions in the ubiquitous language of a specific bounded context. Give the service a name, which also becomes part of the ubiquitous language." Its Layered Architecture entry says: "Isolate the expression of the domain model and the business logic, and eliminate any dependency on infrastructure, user interface, or even application logic that is not business logic", and it already points to hexagonal architecture as an alternative that "may serve as well or better".

Fowler, 2003: the anemic warning. AnemicDomainModel (25 November 2003) quotes Evans's layer descriptions, including "This layer is kept thin", and calls the anti-pattern "really just a procedural style design".

Cockburn, 2005: ports and adapters. Alistair Cockburn's Hexagonal (Ports & Adapters) Architecture (technical report dated 2005-09-04) states the intent: "Allow an application to equally be driven by users, programs, automated test or batch scripts, and to be developed and tested in isolation from its eventual run-time devices and databases." The hexagon has no layers. It has an inside, an outside, and ports between them.

Meyer and Fowler: CQS. Bertrand Meyer's command-query separation, summarised in Fowler's CommandQuerySeparation (5 December 2005): "Queries: Return a result and do not change the observable state of the system... Commands: Change the state of a system but do not return a value." Greg Young later lifted it from methods to whole models as CQRS (see Event Sourcing & CQRS).

Martin, 2012: the dependency rule and use cases. Robert C. Martin's The Clean Architecture (13 August 2012) names "The Dependency Rule. This rule says that source code dependencies can only point inwards." His use-case ring "contains application specific business rules... These use cases orchestrate the flow of data to and from the entities." His "interactor" is the same thing as Evans's application service.

Vernon, 2013, and Khononov, 2021. Vaughn Vernon's Implementing Domain-Driven Design gives domain services their own chapter (7) and covers application services in chapter 14. Vlad Khononov's Learning Domain-Driven Design (O'Reilly, 2021) does the same in its chapters on business-logic patterns and architectural patterns. We did not have either book open while writing this page. We cite them for orientation only and quote nothing from them.

Three Dots Labs, 2020: the Go shape. Miłosz Smółka's Introducing Clean Architecture by refactoring a Go project (1 September 2020) and Robert Laszczak's How to use basic CQRS in Go (28 September 2020) refactor the Wild Workouts example into domain, app/command, app/query, adapters and ports. Their definition of the middle layer: "application logic is a thin layer that 'glues together' other layers. It's also known as 'use cases'." The CQRS article "leads to splitting application services into two separate types: command and query handlers."

text
     Year   Source                                  What it added to "service"
1    2002   Fowler/Stafford, PoEAA Service Layer    Application boundary; transactions live here
2    2003   Evans, DDD (book)                       Domain vs application vs infrastructure services
3    2003   Fowler, AnemicDomainModel               Application layer is thin; rules stay in the domain
4    2005   Cockburn, Hexagonal                     Ports owned by the inside; adapters outside
5    2005   Fowler on Meyer's CQS                   Commands change, queries answer
6    2008   Palermo, Onion Architecture             Same rule, drawn as rings
7    2012   Martin, Clean Architecture              Dependency rule; use cases / interactors
8    2013   Vernon, IDDD (ch. 7, 14)                Domain and application services in practice
9    2015   Evans, DDD Reference                    The definitions quoted on this page
10   2020   Three Dots Labs, Wild Workouts          Go layout: domain, app/command, app/query, adapters, ports

The concept catalogue ​

Ten blocks. The first four are the core; the rest are the mechanics every real use case needs.

Domain service Must-know ​

In plain words: a domain service is a business calculation or decision that needs several domain objects at once, so it does not fit inside any one of them. It is named the way the business names it, keeps no state, and touches no database, network or clock.

Common misunderstanding: "Every aggregate gets a XxxDomainService next to it." No. If the rule only needs the order's own data, it is a method on Order. Moving it to a service makes the entity anemic. A domain service is justified only when the operation spans several aggregates or value objects, or when putting it on one of them would be arbitrary. The classic example: does a transfer belong to the source account or the target account? To neither.

Definition: a stateless operation in the domain layer, expressed in the ubiquitous language, that implements a significant domain process or transformation which is not a natural responsibility of an entity or value object. Its inputs and outputs are domain objects. It has a contract (pre- and post-conditions) stated in the language of one bounded context. It does no I/O. If it needs data from outside, the application service fetches that data first and passes it in.

text
     Who                    What happens                                               Layer
1    PlaceOrderHandler      has: order (3 lines), tier=gold, promotions=[MUG3]          application
2    PlaceOrderHandler      calls pricing.Quote(order, gold, [MUG3])                    application -> domain
3    PricingService         subtotal = sum(unit price x qty)                            domain
4    PricingService         MUG3: 5 mugs >= 3, so 10% off that line                     domain
5    PricingService         gold: 5% off what remains after promotions                  domain
6    PricingService         net >= 50.00, so shipping is free                           domain
7    PricingService         returns Quote{subtotal, discount, shipping, total}          domain -> application
8    PlaceOrderHandler      order.Place(quote, paymentRef, now)                         application -> domain

Real scenarios:

  • Pricing (this chapter): lines + customer tier + active promotions + shipping policy. No single object owns all four.
  • Funds transfer in a wallet: debit one account, credit another, apply the fee policy. The classic Evans/Vernon example.
  • Allocation in Fulfilment: choose a warehouse for each order line by stock, distance and carrier cut-off.
  • Overbooking policy in a booking system: may this cargo booking exceed the voyage capacity by 10%?
  • Tax calculation across lines and a shipping address, when the rules are your own and not a vendor's API. If it is a vendor API, it is an infrastructure service behind a port.

Where it lives, per stack:

StackShapeWiring
GoPlain struct with a pure method in the domain package (sales.PricingService); policy numbers as fieldsConstructed in main as a value; no interface needed unless it has variants
Laravel 13final readonly class in app/Modules/Sales/Domain, no facades, no Eloquent$this->app->singleton(PricingService::class, ...) with config values
Java / SpringPlain class; @Service is a Spring stereotype, not a DDD kindAvoid putting @Transactional on a domain service
.NETClass in the Domain project, no EF Core referenceRegistered in Program.cs; domain project references nothing

Fix / how to use it: keep it pure and test it with a table, as in Go and Laravel. When you are tempted to inject a repository into a domain service, stop. Either the application service loads the data and passes it in, or the domain defines a narrow port (for example, ExchangeRates) and you accept that this service is no longer pure. Say so in its name and its tests.

Application service / use case Must-know ​

In plain words: one class (or function) per thing a user or system wants done: "place an order", "cancel an order", "mark paid". It reads like the user story. It fetches what is needed, asks the domain to decide, saves the result and publishes what happened. It decides nothing itself.

Common misunderstanding: "Thin means it should be three lines." Thin means no business rules, not few lines. PlaceOrderHandler has about 60 lines: idempotency check, reads through three ports, a payment authorization outside the transaction, a compensation, one transaction. All of that is orchestration. Not one line in it computes a price or checks a quantity.

Definition: a stateless object in the application layer that implements one use case. It accepts an input DTO (a command), authorizes and validates it at the edge, loads aggregates through repositories, calls domain behaviour (entities and domain services), persists the changed aggregate inside one transaction, dispatches the domain events it collected, and returns an output DTO or nothing. Fowler's summary of Evans: it "Defines the jobs the software is supposed to do and directs the expressive domain objects to work out problems." Other names for it: use case or interactor (Martin), command handler (CQRS vocabulary, Wild Workouts), Action (Laravel community), application service (Evans, Vernon).

text
     Step  PlaceOrderHandler.Handle(cmd)                         Kind of work
1    1     orders.Get(cmd.OrderID): exists? return replay         idempotency (application)
2    2     catalog.UnitPrices, customers.Tier, promotions.Active  gather inputs via ports
3    3     sales.NewOrder(...)                                    domain: invariants
4    4     pricing.Quote(order, tier, promos)                     domain service
5    5     payments.Authorize(key, total)                         infrastructure, OUTSIDE the tx
6    6     order.Place(quote, ref, now)                           domain: state change + OrderPlaced
7    7     uow.Do: orders.Add(order); outbox.Append(events)       one transaction
8    8     on failure: payments.Void(ref)                         compensation
9    9     return PlaceOrderResult{OrderID, Total}                output DTO

Real scenarios: PlaceOrder, CancelOrder, MarkOrderPaid (driven by Billing's event), ReserveStock, ScheduleShipment, RefundPayment, ChangeShippingAddress. In each one the steps are the same: load, decide, save, publish. Only the domain call in the middle changes.

Granularity: one class per use case or one per aggregate?

StyleShapeGoodWatch out
One handler per use casePlaceOrderHandler, CancelOrderHandlerSmall, one reason to change (SRP), easy to decorateMany files; share helpers sparingly
Grouped service per aggregateOrderApplicationService with place(), cancel()Fewer files, Vernon's IDDD styleGrows into a god service; constructor collects every dependency
Laravel Action (lorisleiva/laravel-actions)One class, handle() plus asController, asJobOne class runs as controller, job, listenerTies the use case to the package; keep domain calls inside handle()
Functionfunc PlaceOrder(deps, cmd)Minimal in GoDependencies travel as arguments; decorators are harder

Fix / how to use it: see the Go handler and the Laravel handler. The review test: read only the application service. If you can tell what discount a gold customer gets, a rule has leaked.

Infrastructure service Must-know ​

In plain words: something the system needs that has nothing to do with the business rules: charge a card, send an email, know the time, make an ID, store a file, call another company's API. The inside describes what it needs as an interface. The outside provides it.

Common misunderstanding: "PaymentService is a domain service because payment is part of our business." The rule "an order must be paid before it ships" is domain. Talking to Stripe is infrastructure. The port is named in the use case's words (Authorize, Void). The adapter speaks Stripe's (PaymentIntent, capture_method=manual, Idempotency-Key).

Definition: a technical capability implemented in the infrastructure layer as an adapter behind a port. The port (interface) is declared by the layer that needs it: the domain for repositories, the application layer for gateways, clocks and outboxes. The adapter is chosen at the composition root. An infrastructure service may hold state that has nothing to do with the business: HTTP clients, connection pools, API keys, retry budgets.

text
     Inside (port owner)            Port                    Adapter (infrastructure)           Test double
1    application: PlaceOrder        PaymentGateway          stripe.Gateway (HTTP, form body)   memory.Payments
2    application: PlaceOrder        Clock                   clock.System (time.Now().UTC())    memory.FixedClock
3    domain: Sales                  OrderRepository         postgres.Orders (database/sql)     memory.Store
4    application: PlaceOrder        Outbox                  postgres.Outbox (INSERT outbox)    memory.Store
5    application: PlaceOrder        Catalog                 local price list / HTTP client     memory.Catalog
6    application: SendReceipt       Mailer                  SMTP / SES / Postmark              array of sent mails

Real scenarios: payment gateways (Stripe, Adyen, PayPal), email and SMS (SES, Postmark, Twilio), object storage (S3, GCS), ID generation (UUIDv7, Snowflake; see ID Generation), the clock, feature flags, geocoding, tax-rate vendors, PDF rendering, and other bounded contexts called over HTTP. The last one sits behind an anticorruption layer (Context Maps).

Per stack:

CapabilityGo adapterLaravel 13 adapterTest double
HTTP API (Stripe)net/http client with timeoutHttp::withToken()->asForm()->post()httptest.Server / Http::fake()
Clocktime.Now().UTC()Date::now()Fixed clock / $this->travelTo()
Emailnet/smtp or provider SDKMail::to()->send()In-memory / Mail::fake()
Queue / brokeramqp091-go, franz-godispatch(), ShouldQueueIn-memory / Queue::fake()
FilesAWS SDK v2 S3Storage::disk('s3')Temp dir / Storage::fake()

Fix / how to use it: the Stripe adapter translates the provider's error into the port's own ErrPaymentDeclined. Callers never import the adapter to recognise a decline. Laravel facades are fine here: the adapter is the one layer allowed to know the framework.

Dependency rule, ports and adapters, composition root Must-know ​

In plain words: the inside (domain and use cases) says what it needs as interfaces. The outside (database, HTTP, Stripe) plugs into those interfaces. One file at start-up decides which plug goes where.

Common misunderstanding: "Hexagonal means every class gets an interface." Ports exist where the inside meets a technology: storage, network, time, randomness. PricingService is a domain value with no variants, so it needs no interface. An interface with exactly one implementation that is not a technology boundary is just indirection.

Definition: the dependency rule (Martin) says source-code dependencies point only inward. Inner code never names an outer type. A port is an interface owned by the inner layer. Cockburn distinguishes driving (primary) ports, through which the outside calls the application, from driven (secondary) ports, through which the application calls the outside. An adapter converts between a technology and a port. The composition root is the single place, usually main or a service provider, where concrete adapters are constructed and injected. This is Dependency Inversion applied at the scale of layers. Three Dots Labs warn about a naming clash: "Our ports are Hexagonal Architecture's Primary Adapters. Our adapters are Hexagonal Architecture's Secondary Adapters." This page uses Cockburn's meaning. Ports are interfaces (app/ports.go), and both the HTTP handler and the Postgres code are adapters.

Driving (primary)Driven (secondary)Application coreUse cases:PlaceOrder, CustomerOrdersDomain: Order,PricingServiceHTTP / Form RequestQueued jobCLI / ArtisanTestOrderRepository:Postgres | memoryPaymentGateway:Stripe | fakeClock:system | fixedOutbox:SQL table | memoryCatalog:price list | HTTPComposition root (main.go / ServiceProvider) plugs adapters into portsarrows = "implements"arrows = "calls"

The map shows the hexagon for Sales. On the left, four driving adapters (HTTP with a Form Request, a queued job, a CLI command, a test) all call the same use cases. On the right, five driven ports each have two interchangeable adapters: Postgres or memory, Stripe or a fake, system or fixed clock, SQL outbox or memory, local price list or HTTP. The composition root at the bottom decides which one is plugged in.

text
     Moment         What runs                                         Knows concrete types?
1    start-up       main(): open DB, build stripe.Gateway, clock      yes: only here
2    start-up       main(): PlaceOrderHandler{UoW: pg, Payments: ...} yes: only here
3    start-up       main(): wrap with decorator.Logging               yes: only here
4    request        httpapi.PlaceOrder decodes JSON -> command        no: knows the handler interface
5    request        handler.Handle(ctx, cmd)                          no: knows ports
6    request        stripe.Gateway.Authorize                          yes, of its own technology only

Real scenarios: swapping Firestore for MySQL in Wild Workouts by writing a new adapter (hour_mysql_repository.go next to hour_firestore_repository.go); running the whole use case in tests against memory.Store; replacing Stripe with Adyen in one market; pointing the query handler at a read replica.

Where wiring lives:

StackComposition rootDI style
Gocmd/<app>/main.go or a service.NewApplication() (Wild Workouts)Manual constructor injection; optional google/wire code generation
Laravel 13Service provider: $bindings property, register() with singleton, bind, extendContainer auto-wiring of constructor type hints
Spring@Configuration classes, component scanAnnotation-driven container
.NETProgram.cs with builder.Services.AddScoped<IPort, Adapter>()Built-in container

Fix / how to use it: enforce the rule mechanically. The Go module has a test that fails if sales imports database/sql, net/http, log/slog, os or any app or adapter package. In Laravel, Pest's architecture testing or Deptrac does the same; Layered Monolith shows both.

Command and query handlers Important ​

In plain words: split application services into two kinds. Ones that change something and return (almost) nothing, and ones that return something and change nothing.

Common misunderstanding: "CQS at the application layer means CQRS with two databases and event sourcing." No. Separate command and query handlers can read and write the same tables. CQRS, with separate read models kept up to date by events, is an optional next step (Event Sourcing & CQRS, Data Patterns in Microservices).

Definition: command-query separation (Meyer, via Fowler) applied to use cases. A command handler takes a command DTO, goes through an aggregate and a transaction, raises events, and returns nothing or a minimal result (the new id, a total, a replay flag). A query handler takes a query DTO, reads directly from tables, a view, a replica or a cache, loads no aggregate, opens no write transaction, and returns DTOs shaped for the caller. Wild Workouts wires them as app.Application{Commands: ..., Queries: ...}.

text
     Request                       Handler                        Touches                      Returns
1    POST /orders                  PlaceOrderHandler              Order aggregate, tx, outbox  {order_id, total}
2    GET /customers/c-1/orders     CustomerOrdersHandler          SELECT ... LIMIT 20          [OrderSummary]
3    POST /orders/o-1/cancel       CancelOrderHandler             Order aggregate, tx, outbox  204
4    GET /orders/o-1               OrderDetailsHandler            view / replica               OrderDetails

Real scenarios: the "My orders" page reads a denormalized order_summaries view on a replica while PlaceOrder writes to the primary. The admin dashboard reads a cache that is rebuilt from OrderPlaced events. An export job calls a query handler with a cursor (Cursors & Streaming).

Returns dataChanges stateTypical storeCan it be cached?
Command handlerMinimal (id, total)YesPrimary databaseNo
Query handlerYesNoReplica, view, cache, search indexYes
"Command that returns the full object"YesYesPrimaryHard to cache; a common compromise

Fix / how to use it: Go app/query and Laravel Queries/CustomerOrdersHandler. Notice that the query handler has no repository and no domain object.

Transactions and the unit of work Must-know ​

In plain words: the application service decides where the database transaction starts and ends. The domain does not know transactions exist. One use case usually means one transaction that changes one aggregate.

Common misunderstanding: "Wrap the whole handler in a transaction, it is safer." Not if the handler calls Stripe. A network call inside a transaction holds a database connection and row locks for as long as the provider takes. Then the call succeeds while the commit fails, and you have charged a card for an order that does not exist. Keep external calls outside the transaction and compensate them.

Definition: a unit of work (Fowler, PoEAA) tracks the changes made during one business transaction and commits them atomically. In this chapter it is a port, UnitOfWork.Do(ctx, fn) in Go and UnitOfWork::run(callable) in Laravel. It hands fn repositories and an outbox bound to one database transaction: commit if fn returns normally, roll back otherwise. The rule from Aggregates still holds: one aggregate per transaction, and other aggregates are updated by events, eventually. The isolation level is the database's default unless the use case needs more (Isolation Levels).

text
     T    Application service                       Database                           Stripe
1    t0   Get(o-1): not found                       SELECT ... (no tx)
2    t1   Authorize(order-o-1, 66.50)                                                  PaymentIntent pi_1 (requires_capture)
3    t2   order.Place(...)                          (nothing yet)
4    t3   uow.Do: BEGIN                             BEGIN
5    t4     INSERT sales_orders, sales_order_lines  rows locked by this tx
6    t5     INSERT outbox (sales.order.placed.v1)
7    t6   COMMIT                                    COMMIT: order and event durable together
8    t6'  if COMMIT fails: Void(pi_1)                                                  pi_1 canceled

Real scenarios: a payment provider timeout of 30 s inside a transaction exhausts the connection pool (Connection Pooling). A deadlock between two use cases that touch two aggregates in different orders (Deadlocks). A Laravel listener that writes to a second connection outside the transaction, which never rolls back.

StackTransaction APIRetry on deadlock / serialization failure
Go database/sqldb.BeginTx(ctx, opts), tx.Commit(), tx.Rollback()Your loop on SQLSTATE 40001 / 40P01
pgxpgx.BeginFunc(ctx, db, fn)Your loop
Laravel 13DB::transaction(fn, attempts), ConnectionInterface::transactionSecond argument retries the closure when a deadlock occurs
Spring@Transactional on the application service@Retryable

Fix / how to use it: Go postgres.UnitOfWork and Laravel DatabaseUnitOfWork. Both are adapters behind the port, so the use case never imports database/sql or the DB facade.

Domain events from the use case Important ​

In plain words: the aggregate writes down "OrderPlaced" when it changes. The application service takes those notes and stores them together with the order. Something else delivers them after the save has really happened.

Common misunderstanding: "Dispatch the event right after order.Place()." If the transaction then rolls back, Fulfilment has already started picking an order that does not exist. Events leave the process only after commit.

Definition: the aggregate records domain events in memory (PullEvents()/pullEvents()). The application service collects them and writes them, in the same transaction as the aggregate, either to an outbox table that a relay publishes after commit (Outbox Pattern) or to an in-process dispatcher that holds them until commit. Laravel 13 provides the second option: an event implementing ShouldDispatchAfterCommit is dispatched only after the open transaction commits ("If the transaction fails, the event will be discarded"), and a job can be dispatched with ->afterCommit(). Domain events versus integration events, and their payloads, are covered in Domain Events vs Integration Events.

text
     Option                         Same tx as order?   Survives crash after commit?   Leaves the process?
1    dispatch before commit         no                  n/a: may announce a rollback   yes: wrong
2    ShouldDispatchAfterCommit      held until commit   no: lost if process dies       in-process listeners
3    job ->afterCommit()            pushed after commit no: lost if process dies       yes, via queue
4    outbox row + relay             yes                 yes                            yes: at-least-once

Real scenarios: OrderPlaced → Fulfilment reserves stock and Billing captures on shipment (Saga Pattern). OrderPlaced → send the receipt email (an in-process listener is fine; losing one email on a crash is acceptable to some businesses). OrderPlaced → update the "My orders" projection. Event-driven styles beyond one use case are covered in Event-Driven Architecture.

Fix / how to use it: both implementations append order.PullEvents() to the Outbox port inside uow.Do. Consumers must still be idempotent, because the relay delivers at least once (Idempotent Consumers & Inbox).

Cross-cutting concerns as decorators Important ​

In plain words: logging, metrics, tracing, authorization checks, retries and idempotency are wrapped around the use case, like layers of an onion, instead of being written inside it.

Common misunderstanding: "Decorators replace authorization in the domain." Two different things are both called authorization. May this user call this use case at all? belongs at the edge (Form Request authorize(), a decorator, middleware). May this order be cancelled after shipping? is a domain rule and stays in the aggregate.

Definition: a decorator (Structural Patterns) implements the same interface as the handler, does its work, and delegates to the wrapped handler. Wild Workouts applies decorator.ApplyCommandDecorators (logging plus metrics) to every handler. Laravel's container offers the same through extend: "you may run additional code to decorate or configure the service." HTTP middleware is the same idea one layer further out. Laravel's Context adds a correlation id that "is automatically appended as metadata to any log entries" and travels with queued jobs.

text
     Call chain for POST /orders
1    AssignCorrelationId middleware   Context::add('correlation_id', ...)
2    PlaceOrderRequest                authorize(): can('place-orders'); rules(): shape
3    LogsPlaceOrder (decorator)       start timer
4    PlaceOrderHandler                the use case
5    LogsPlaceOrder (decorator)       log ok/failed + duration (with correlation_id)
6    Controller                       map result / exception to HTTP status
ConcernWhere it goesGoLaravel 13
Logging, timingDecoratordecorator.Logging with log/slogLogsPlaceOrder via $this->app->extend()
MetricsDecoratordecorator.Measured over a Metrics portDecorator calling a metrics client
Correlation idEdge middlewarecontext.Context valueContext::add() in middleware
Use-case authorizationEdge or decoratordecorator.AuthorizedForm Request authorize(), Gate, policies
IdempotencyNatural key in the use case, or decoratorOrderID as key; decorator.Idempotent for keyless commandsIdempotency-Key header as order id; middleware variant
Retry on conflictDecorator around the use caseapp.Retry loop on ErrConcurrencyConflict, as in Aggregates (not in this module)DB::transaction($fn, 3) for deadlocks

Fix / how to use it: Go decorators and the Laravel provider.

DTOs and validation at the edge Important ​

In plain words: the use case takes a small, plain input object and returns a small, plain output object. Checking that the JSON has the right shape happens before the use case. Checking business rules happens inside the domain.

Common misunderstanding: "Validation lives in one place." There are two kinds. Shape validation (required, integer, array, max length) belongs to the edge: a Form Request, or the HTTP adapter's decoder. Rule validation (at most 50 per line, the order must be a draft) belongs to the domain, because it must hold for the queue job and the CLI too. Duplicating a rule at the edge for a nicer error message is fine, as long as the domain still enforces it.

Definition: the input DTO (command) is an immutable data object with primitive or value-object fields and no behaviour: PlaceOrder{OrderID, CustomerID, Items, PaymentToken}. The output DTO is what the caller needs: PlaceOrderResult{OrderID, Total, Replay}. Neither is the aggregate. Returning the aggregate leaks domain internals to controllers and invites them to call its methods. Laravel's docs describe Form Requests as "custom request classes that encapsulate their own validation and authorization logic". Here the Form Request's job ends with toCommand().

text
     Layer          Sees                                      Rejects with
1    HTTP adapter   JSON body, headers                        422 shape error, 428 no Idempotency-Key
2    Form Request   validated array                           403 (authorize), 422 (rules)
3    Use case       PlaceOrder DTO                            nothing of its own
4    Domain         OrderLine(quantity=99)                    OrderRuleViolated -> 422
5    Adapter        Stripe 402 card_error                     PaymentDeclined -> 402

Real scenarios: the same PlaceOrder DTO built from HTTP, a CSV import job and a CLI artisan orders:place. A GraphQL resolver that maps to the same command. An API version 2 that changes the JSON but not the command.

Fix / how to use it: Laravel PlaceOrderRequest::toCommand(), Go httpapi.PlaceOrder.

Naming: the "Service" suffix Good to know ​

In plain words: a class name ending in Service, Manager, Helper or Processor tells you nothing about what it does. Name it after the operation or the concept, as the business would say it.

Common misunderstanding: "DDD requires the suffix so we know it is a service." Evans asks that the service's name be part of the ubiquitous language. PricingService passes that test because the business talks about "pricing". OrderService does not, because it is a bucket for anything that touches orders.

Definition: a naming convention, not a pattern. Use cases are verbs (PlaceOrder, CancelOrder). Domain services are domain nouns or verbs (PricingService, Overbooking, FundsTransfer). Infrastructure adapters are named after their technology (StripePaymentGateway, SmtpMailer). Ports are named after the capability (PaymentGateway, Clock). Go's package naming advice pushes the same way: pricing.Quote reads better than services.PricingService.Quote.

text
     Name in the codebase       What it really is                Better name
1    OrderService               god class                        PlaceOrder, CancelOrder, PricingService
2    PaymentService             Stripe client                    StripePaymentGateway (behind PaymentGateway)
3    OrderManager               repository + rules               OrderRepository + methods on Order
4    TimeService                clock                            Clock
5    OrderHelper::total()       pricing rule                     PricingService.Quote or Order.Total

Fix / how to use it: rename during the refactoring in Solving the classic problems.

Mechanics ​

The request lifecycle step by step Must-know ​

HTTP adapterPlaceOrderHandlerOrder +PricingServicePaymentGatewayUoW: repo+ outboxRelay / broker1 PlaceOrder DTO2 Get(orderID): not found, so not a replay3 prices, tier, promotions via ports4 NewOrder, QuoteQuote5 Authorize(key, total): outside the tx6 Place: OrderPlaced7 BEGIN; Add(order); Append(events); COMMITone transaction: aggregate and events commit together or not at all8 after commit9 result DTO, 201

The sequence diagram follows one POST /orders across six lifelines. The HTTP adapter sends the PlaceOrder DTO (1). The handler checks idempotency (2), reads prices, tier and promotions through ports (3), builds the order and gets a quote from PricingService (4), and authorizes payment outside any transaction (5). Place records OrderPlaced (6), and the order and its events are saved in one transaction (7). The relay publishes after commit (8), and the HTTP adapter answers 201 (9).

  1. Edge. Middleware sets the correlation id. The adapter or Form Request checks the shape and the caller's right to run the use case, then builds the command DTO.
  2. Decorators. Logging, metrics and, where used, the idempotency decorator wrap the handler.
  3. Idempotency read. The command's natural key (OrderID taken from the Idempotency-Key header) is looked up. A hit returns the stored result with Replay=true.
  4. Inputs. Prices, tier and promotions come through ports. In a modular monolith they are local read models fed by Catalog's and Identity's events, never those modules' tables.
  5. Domain. NewOrder checks line invariants. PricingService.Quote prices. Nothing here can fail for technical reasons.
  6. External side effect. PaymentGateway.Authorize with the idempotency key order-<id>. Stripe saves "the status code and body of the first request made with a given idempotency key" and returns it on retries.
  7. State change. order.Place(quote, ref, now) records OrderPlaced.
  8. Transaction. Insert the order, its lines and the outbox rows, then commit. On a primary-key violation (a concurrent duplicate), return the winner's result and do not void: both requests share one authorization. On any other failure, void the authorization.
  9. After commit. The outbox relay publishes. In-process ShouldDispatchAfterCommit listeners run.

Tables and the transaction in SQL ​

The Sales tables behind the adapters, and what the unit of work sends to PostgreSQL for one command:

sql
-- Sales owns these tables; no other module writes to them.
CREATE TABLE sales_orders (
    id           text PRIMARY KEY,            -- client-generated: the idempotency key
    customer_id  text        NOT NULL,
    status       text        NOT NULL,
    total_minor  bigint,
    currency     char(3),
    payment_ref  text,
    placed_at    timestamptz
);
CREATE TABLE sales_order_lines (
    order_id   text     NOT NULL REFERENCES sales_orders(id) ON DELETE CASCADE,
    position   smallint NOT NULL,
    sku        text     NOT NULL,
    quantity   smallint NOT NULL CHECK (quantity BETWEEN 1 AND 50),  -- defence in depth
    unit_minor bigint   NOT NULL,
    PRIMARY KEY (order_id, position)
);
CREATE TABLE outbox (
    id           bigserial PRIMARY KEY,
    event_name   text        NOT NULL,
    payload      jsonb       NOT NULL,
    created_at   timestamptz NOT NULL DEFAULT now(),
    published_at timestamptz
);
CREATE INDEX outbox_unpublished ON outbox (id) WHERE published_at IS NULL;

-- One PlaceOrder command = one transaction (READ COMMITTED, the PostgreSQL default).
BEGIN;
INSERT INTO sales_orders (id, customer_id, status, total_minor, currency, payment_ref, placed_at)
VALUES ('o-1001', 'c-gold', 'placed', 6650, 'EUR', 'pi_3Q...', now());
INSERT INTO sales_order_lines VALUES ('o-1001', 0, 'MUG', 5, 1200), ('o-1001', 1, 'TEA', 2, 800);
INSERT INTO outbox (event_name, payload)
VALUES ('sales.order.placed.v1', '{"order_id":"o-1001","total_minor":6650,"currency":"EUR"}');
COMMIT;

-- A concurrent duplicate fails on the first INSERT:
-- ERROR:  duplicate key value violates unique constraint "sales_orders_pkey"  (SQLSTATE 23505)

The CHECK constraint repeats a domain rule as a safety net. The rule's home is still OrderLine. The database copy only catches code that bypasses the domain.

Errors you will see, and which layer translates them ​

ErrorRaised byTranslated byIntoHTTP
quantity must be between 1 and 50Domain (ErrBadQuantity, OrderRuleViolated)Driving adapterMessage for the user422
SQLSTATE 23505 unique_violation (PostgreSQL), error 1062 ER_DUP_ENTRY (MySQL)DatabaseRepository adapterErrDuplicateOrder / DuplicateOrder200 replay
Illuminate\Database\UniqueConstraintViolationExceptionLaravel query builderEloquentOrderRepositoryDuplicateOrder200 replay
SQLSTATE 40001 serialization_failure, 40P01 deadlock_detected; MySQL 1213DatabaseRetry decorator / DB::transaction($fn, 3) (recommended; not in this stub, because the closure would need to re-pull events)Retry, then 503503
Stripe 402 with error.type = card_error, code = card_declinedStripestripe.Gateway / StripePaymentGatewayErrPaymentDeclined / PaymentDeclined402
Stripe 409 "conflicts with another request (perhaps due to using the same idempotent key)"StripeAdapterRetry after a short wait (recommended; the stub surfaces it as an error)409 / retry
AuthorizationException (Form Request authorize() returned false)LaravelFramework403403
ValidationExceptionForm Request rulesFramework422 with field errors422
context deadline exceededGo contexthttpapi (errors.Is(err, context.DeadlineExceeded))Timeout504

The rule behind the table: errors are translated at the boundary they cross. The domain never sees 23505, and the controller never sees card_error.

Go ​

The module academy/domain-application-infrastructure-services follows the Wild Workouts shape: sales (domain), app (ports), app/command and app/query (use cases), app/decorator, adapters/*, cmd/shop (composition root). gofmt -l . and go vet ./... are clean, and go test ./... passes.

Domain: the aggregate, the port and the domain service ​

go
// Package sales is the domain layer of the Sales bounded context. It imports
// nothing from the application or infrastructure layers: no SQL, no HTTP, no
// clock, no logger. Everything it needs from the outside is passed in.
package sales

import (
	"errors"
	"time"
)

type (
	// OrderID is the identity of the Order aggregate. The client may supply it,
	// which makes PlaceOrder naturally idempotent.
	OrderID string
	// CustomerID references a customer in the Identity context by id.
	CustomerID string
	// SKU references a Catalog product by id.
	SKU string
)

// Status is the Order lifecycle.
type Status string

// Order states used in this chapter.
const (
	Draft  Status = "draft"
	Placed Status = "placed"
)

// Domain errors, phrased in the ubiquitous language.
var (
	ErrEmptyOrder     = errors.New("an order needs at least one line")
	ErrBadQuantity    = errors.New("quantity must be between 1 and 50")
	ErrAlreadyPlaced  = errors.New("the order has already been placed")
	ErrQuoteMismatch  = errors.New("the quote was made for another order")
	ErrOrderNotFound  = errors.New("order not found")
	ErrDuplicateOrder = errors.New("an order with this id already exists")
)

// Line is one order line: a SKU, a quantity and the catalogue unit price.
type Line struct {
	SKU       SKU
	Quantity  int
	UnitPrice Money
}

// Order is the aggregate root.
type Order struct {
	id       OrderID
	customer CustomerID
	lines    []Line
	status   Status
	total    Money
	payment  string
	placedAt time.Time
	events   []Event
}

// NewOrder creates a draft order and checks the line invariants.
func NewOrder(id OrderID, customer CustomerID, lines []Line) (*Order, error) {
	if len(lines) == 0 {
		return nil, ErrEmptyOrder
	}
	for _, l := range lines {
		if l.Quantity < 1 || l.Quantity > 50 {
			return nil, ErrBadQuantity
		}
	}
	cp := append([]Line(nil), lines...)
	return &Order{id: id, customer: customer, lines: cp, status: Draft}, nil
}

// Place freezes the priced total, stores the payment reference and records
// OrderPlaced. The time is an argument: the domain never reads a clock.
func (o *Order) Place(q Quote, paymentRef string, now time.Time) error {
	if o.status != Draft {
		return ErrAlreadyPlaced
	}
	if q.OrderID != o.id {
		return ErrQuoteMismatch
	}
	o.status, o.total, o.payment, o.placedAt = Placed, q.Total, paymentRef, now
	o.events = append(o.events, OrderPlaced{
		OrderID: o.id, CustomerID: o.customer, Total: q.Total, PaymentRef: paymentRef, PlacedAt: now,
	})
	return nil
}

// PullEvents returns the recorded events and clears them, so a retry of the
// same in-memory object cannot publish them twice.
func (o *Order) PullEvents() []Event {
	ev := o.events
	o.events = nil
	return ev
}

// Read-only accessors.
func (o *Order) ID() OrderID            { return o.id }
func (o *Order) Customer() CustomerID   { return o.customer }
func (o *Order) Lines() []Line          { return append([]Line(nil), o.lines...) }
func (o *Order) Status() Status         { return o.status }
func (o *Order) Total() Money           { return o.total }
func (o *Order) PaymentRef() string     { return o.payment }
func (o *Order) PlacedAt() time.Time    { return o.placedAt }
func (o *Order) PendingEvents() []Event { return append([]Event(nil), o.events...) }

// Rehydrate rebuilds an Order from storage. Only repositories call it.
func Rehydrate(id OrderID, customer CustomerID, lines []Line, status Status, total Money, payment string, placedAt time.Time) *Order {
	return &Order{id: id, customer: customer, lines: lines, status: status, total: total, payment: payment, placedAt: placedAt}
}
go
package sales

import "context"

// OrderRepository is a port DEFINED BY THE DOMAIN and implemented in
// adapters/postgres and adapters/memory. The domain owns the interface;
// infrastructure owns the SQL.
type OrderRepository interface {
	Get(ctx context.Context, id OrderID) (*Order, error)
	Add(ctx context.Context, o *Order) error
}
go
package sales

import "fmt"

// Tier is the loyalty tier of a customer, as Sales understands it.
type Tier string

// Tiers known to the pricing policy.
const (
	TierStandard Tier = "standard"
	TierGold     Tier = "gold"
)

// Promotion is a value object: "buy MinQty of SKU, get PercentOff on that line".
type Promotion struct {
	Code       string
	SKU        SKU
	MinQty     int
	PercentOff int
}

// Quote is the result of pricing: a value object, not an entity.
type Quote struct {
	OrderID  OrderID
	Subtotal Money
	Discount Money
	Shipping Money
	Total    Money
}

// PricingService is a DOMAIN service. Pricing is a significant domain
// operation that belongs to no single entity: it combines the order lines,
// the customer's tier and the active promotions. It is stateless, has no I/O
// and speaks only the ubiquitous language, so it is a plain struct with a
// pure method. Policy numbers are fields, set once at wiring time.
type PricingService struct {
	GoldPercentOff    int   // e.g. 5
	FreeShippingFrom  int64 // minor units, e.g. 5000 = 50.00
	FlatShippingMinor int64 // e.g. 495 = 4.95
}

// Quote prices an order. Rules, in order:
//  1. subtotal = sum(unit price x quantity)
//  2. a line promotion applies when quantity >= MinQty (best one per line)
//  3. gold customers get GoldPercentOff on the subtotal after promotions
//  4. shipping is free from FreeShippingFrom, else a flat fee
func (p PricingService) Quote(o *Order, tier Tier, promos []Promotion) (Quote, error) {
	cur := o.lines[0].UnitPrice.Currency
	sub, disc := Money{Currency: cur}, Money{Currency: cur}
	for _, l := range o.lines {
		lineTotal := l.UnitPrice.Times(l.Quantity)
		var err error
		if sub, err = sub.Add(lineTotal); err != nil {
			return Quote{}, fmt.Errorf("pricing %s: %w", l.SKU, err)
		}
		best := 0
		for _, pr := range promos {
			if pr.SKU == l.SKU && l.Quantity >= pr.MinQty && pr.PercentOff > best {
				best = pr.PercentOff
			}
		}
		disc, _ = disc.Add(lineTotal.PercentOff(best))
	}
	afterPromos := sub.Sub(disc)
	if tier == TierGold {
		loyalty := afterPromos.PercentOff(p.GoldPercentOff)
		disc, _ = disc.Add(loyalty)
	}
	net := sub.Sub(disc)
	ship := Money{Minor: p.FlatShippingMinor, Currency: cur}
	if net.Minor >= p.FreeShippingFrom {
		ship = Money{Currency: cur}
	}
	total, _ := net.Add(ship)
	return Quote{OrderID: o.id, Subtotal: sub, Discount: disc, Shipping: ship, Total: total}, nil
}

Application: ports, the command handler, the query handler, decorators ​

go
// Package app holds the ports the application layer needs from the outside
// world. They are interfaces owned by the inside and implemented by adapters
// (Cockburn's ports and adapters; DIP at the architectural level).
package app

import (
	"context"
	"errors"
	"time"

	"academy/domain-application-infrastructure-services/sales"
)

// Clock is an infrastructure-service port: "what time is it?"
type Clock interface{ Now() time.Time }

// ErrPaymentDeclined is the port's own error. Adapters wrap their provider's
// error into it, so callers never import an adapter to recognise a decline.
var ErrPaymentDeclined = errors.New("payment declined")

// PaymentGateway is an infrastructure-service port. The use case speaks in
// its own terms (authorize, void); the Stripe adapter translates.
type PaymentGateway interface {
	// Authorize reserves the amount. idempotencyKey makes a retried call safe.
	Authorize(ctx context.Context, idempotencyKey string, amount sales.Money, paymentToken string) (ref string, err error)
	// Void releases an authorization that will never be captured.
	Void(ctx context.Context, ref string) error
}

// Catalog is an anticorruption port to the Catalog context: current unit prices.
type Catalog interface {
	UnitPrices(ctx context.Context, skus []sales.SKU) (map[sales.SKU]sales.Money, error)
}

// Customers answers Sales' only question about a customer: the pricing tier.
type Customers interface {
	Tier(ctx context.Context, id sales.CustomerID) (sales.Tier, error)
}

// Promotions returns the promotions active at a moment.
type Promotions interface {
	Active(ctx context.Context, at time.Time) ([]sales.Promotion, error)
}

// Outbox stores events in the same transaction as the aggregate; a relay
// publishes them after commit (see the Outbox Pattern chapter).
type Outbox interface {
	Append(ctx context.Context, events ...sales.Event) error
}

// Tx is what a unit of work hands to the use case: repositories and the
// outbox, all bound to ONE database transaction.
type Tx interface {
	Orders() sales.OrderRepository
	Outbox() Outbox
}

// UnitOfWork runs fn in one transaction: commit if fn returns nil, else rollback.
type UnitOfWork interface {
	Do(ctx context.Context, fn func(ctx context.Context, tx Tx) error) error
}
go
// Package command holds the write-side application services (use cases).
package command

import (
	"context"
	"errors"
	"fmt"

	"academy/domain-application-infrastructure-services/app"
	"academy/domain-application-infrastructure-services/sales"
)

// PlaceOrder is the input DTO (the command). Plain data, already validated
// for shape at the edge (HTTP adapter); business rules are checked inside.
type PlaceOrder struct {
	OrderID      sales.OrderID // client-generated: doubles as the idempotency key
	CustomerID   sales.CustomerID
	Items        []Item
	PaymentToken string
}

// Item is one requested line, without a price: prices come from Catalog.
type Item struct {
	SKU      sales.SKU
	Quantity int
}

// PlaceOrderResult is the output DTO.
type PlaceOrderResult struct {
	OrderID sales.OrderID
	Total   sales.Money
	Replay  bool // true when the same command was already handled
}

// PlaceOrderHandler is an APPLICATION service: it orchestrates and decides
// nothing about prices, discounts or order rules itself.
type PlaceOrderHandler struct {
	UoW        app.UnitOfWork
	Orders     sales.OrderRepository // for the idempotency read outside the tx
	Catalog    app.Catalog
	Customers  app.Customers
	Promotions app.Promotions
	Payments   app.PaymentGateway
	Clock      app.Clock
	Pricing    sales.PricingService // domain service, a value: no interface needed
}

// Handle runs the use case.
func (h PlaceOrderHandler) Handle(ctx context.Context, cmd PlaceOrder) (PlaceOrderResult, error) {
	// 1. Idempotency: the same OrderID twice returns the first result.
	if existing, err := h.Orders.Get(ctx, cmd.OrderID); err == nil {
		return PlaceOrderResult{OrderID: existing.ID(), Total: existing.Total(), Replay: true}, nil
	} else if !errors.Is(err, sales.ErrOrderNotFound) {
		return PlaceOrderResult{}, err
	}

	// 2. Gather the inputs the domain needs (reads through ports).
	skus := make([]sales.SKU, 0, len(cmd.Items))
	for _, it := range cmd.Items {
		skus = append(skus, it.SKU)
	}
	prices, err := h.Catalog.UnitPrices(ctx, skus)
	if err != nil {
		return PlaceOrderResult{}, fmt.Errorf("catalog: %w", err)
	}
	lines := make([]sales.Line, 0, len(cmd.Items))
	for _, it := range cmd.Items {
		p, ok := prices[it.SKU]
		if !ok {
			return PlaceOrderResult{}, fmt.Errorf("unknown sku %q", it.SKU)
		}
		lines = append(lines, sales.Line{SKU: it.SKU, Quantity: it.Quantity, UnitPrice: p})
	}
	tier, err := h.Customers.Tier(ctx, cmd.CustomerID)
	if err != nil {
		return PlaceOrderResult{}, fmt.Errorf("customers: %w", err)
	}
	now := h.Clock.Now()
	promos, err := h.Promotions.Active(ctx, now)
	if err != nil {
		return PlaceOrderResult{}, fmt.Errorf("promotions: %w", err)
	}

	// 3. Domain: the aggregate checks its invariants, the domain service prices.
	order, err := sales.NewOrder(cmd.OrderID, cmd.CustomerID, lines)
	if err != nil {
		return PlaceOrderResult{}, err
	}
	quote, err := h.Pricing.Quote(order, tier, promos)
	if err != nil {
		return PlaceOrderResult{}, err
	}

	// 4. Infrastructure service, OUTSIDE the database transaction: never hold
	// row locks while waiting on a payment provider.
	ref, err := h.Payments.Authorize(ctx, "order-"+string(order.ID()), quote.Total, cmd.PaymentToken)
	if err != nil {
		return PlaceOrderResult{}, fmt.Errorf("payment: %w", err)
	}
	if err := order.Place(quote, ref, now); err != nil {
		_ = h.Payments.Void(ctx, ref)
		return PlaceOrderResult{}, err
	}

	// 5. One transaction: save the aggregate and its events together.
	err = h.UoW.Do(ctx, func(ctx context.Context, tx app.Tx) error {
		if err := tx.Orders().Add(ctx, order); err != nil {
			return err
		}
		return tx.Outbox().Append(ctx, order.PullEvents()...)
	})
	if errors.Is(err, sales.ErrDuplicateOrder) {
		// A concurrent request with the same OrderID won the race. Both used the
		// same idempotency key, so they share ONE authorization: voiding it here
		// would cancel the winner's payment. Return the winner's result instead.
		winner, gerr := h.Orders.Get(ctx, cmd.OrderID)
		if gerr != nil {
			return PlaceOrderResult{}, gerr
		}
		return PlaceOrderResult{OrderID: winner.ID(), Total: winner.Total(), Replay: true}, nil
	}
	if err != nil {
		// Compensate the side effect we cannot roll back with SQL.
		_ = h.Payments.Void(ctx, ref)
		return PlaceOrderResult{}, err
	}
	return PlaceOrderResult{OrderID: order.ID(), Total: quote.Total}, nil
}
go
// Package query holds the read-side application services. A query handler
// changes nothing, loads no aggregate and may read a denormalized view.
package query

import (
	"context"
	"time"
)

// OrderSummary is the output DTO, shaped for the screen, not for the domain.
type OrderSummary struct {
	OrderID    string
	Status     string
	TotalMinor int64
	Currency   string
	PlacedAt   time.Time
	Lines      int
}

// OrderSummaries is the read-model port (a SQL view, a replica, a cache...).
type OrderSummaries interface {
	ForCustomer(ctx context.Context, customerID string, limit int) ([]OrderSummary, error)
}

// CustomerOrders is the query.
type CustomerOrders struct {
	CustomerID string
	Limit      int
}

// CustomerOrdersHandler returns data; it never mutates state (CQS).
type CustomerOrdersHandler struct{ ReadModel OrderSummaries }

// Handle runs the query.
func (h CustomerOrdersHandler) Handle(ctx context.Context, q CustomerOrders) ([]OrderSummary, error) {
	if q.Limit <= 0 || q.Limit > 100 {
		q.Limit = 20
	}
	return h.ReadModel.ForCustomer(ctx, q.CustomerID, q.Limit)
}
go
// Package decorator wraps any command handler with cross-cutting concerns
// (logging, metrics, authorization) without touching the use case itself.
package decorator

import (
	"context"
	"errors"
	"log/slog"
	"time"
)

// Handler is the shape every command handler shares.
type Handler[C, R any] interface {
	Handle(ctx context.Context, cmd C) (R, error)
}

// HandlerFunc adapts a function to Handler.
type HandlerFunc[C, R any] func(ctx context.Context, cmd C) (R, error)

// Handle implements Handler.
func (f HandlerFunc[C, R]) Handle(ctx context.Context, cmd C) (R, error) { return f(ctx, cmd) }

// Logging logs every execution with its duration and outcome.
func Logging[C, R any](name string, log *slog.Logger, next Handler[C, R]) Handler[C, R] {
	return HandlerFunc[C, R](func(ctx context.Context, cmd C) (R, error) {
		start := time.Now()
		r, err := next.Handle(ctx, cmd)
		log.InfoContext(ctx, "command handled", "command", name,
			"duration_ms", time.Since(start).Milliseconds(), "ok", err == nil)
		return r, err
	})
}

// Metrics counts calls and failures through a tiny port (Prometheus, OTel...).
type Metrics interface {
	Inc(name string, labels ...string)
}

// Measured records one counter per outcome.
func Measured[C, R any](name string, m Metrics, next Handler[C, R]) Handler[C, R] {
	return HandlerFunc[C, R](func(ctx context.Context, cmd C) (R, error) {
		r, err := next.Handle(ctx, cmd)
		outcome := "ok"
		if err != nil {
			outcome = "error"
		}
		m.Inc("commands_total", "command", name, "outcome", outcome)
		return r, err
	})
}

// ErrForbidden is returned by Authorized.
var ErrForbidden = errors.New("forbidden")

// Authorized asks a policy before running the use case.
func Authorized[C, R any](allow func(ctx context.Context, cmd C) bool, next Handler[C, R]) Handler[C, R] {
	return HandlerFunc[C, R](func(ctx context.Context, cmd C) (R, error) {
		if !allow(ctx, cmd) {
			var zero R
			return zero, ErrForbidden
		}
		return next.Handle(ctx, cmd)
	})
}

// Results remembers the result of a command by idempotency key (a table with
// a unique key, Redis SET NX, ...). Put returns false if the key already exists.
type Results[R any] interface {
	Get(ctx context.Context, key string) (R, bool, error)
	Put(ctx context.Context, key string, r R) (bool, error)
}

// Idempotent is the decorator variant of idempotency: useful when the use
// case has no natural key of its own. PlaceOrder does not need it, because
// its OrderID already is the key and the primary key enforces it.
func Idempotent[C, R any](key func(C) string, store Results[R], next Handler[C, R]) Handler[C, R] {
	return HandlerFunc[C, R](func(ctx context.Context, cmd C) (R, error) {
		k := key(cmd)
		if r, ok, err := store.Get(ctx, k); err != nil || ok {
			return r, err
		}
		r, err := next.Handle(ctx, cmd)
		if err != nil {
			return r, err
		}
		_, perr := store.Put(ctx, k, r)
		return r, perr
	})
}

Infrastructure: Postgres, Stripe, HTTP ​

go
// Package postgres implements the Sales ports with database/sql. It is the
// only package that knows table names, SQL and SQLSTATE codes.
package postgres

import (
	"context"
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"
	"strings"
	"time"

	"academy/domain-application-infrastructure-services/app"
	"academy/domain-application-infrastructure-services/sales"
)

// querier is satisfied by both *sql.DB and *sql.Tx.
type querier interface {
	ExecContext(ctx context.Context, q string, args ...any) (sql.Result, error)
	QueryRowContext(ctx context.Context, q string, args ...any) *sql.Row
	QueryContext(ctx context.Context, q string, args ...any) (*sql.Rows, error)
}

// UnitOfWork opens one *sql.Tx per use case.
type UnitOfWork struct{ DB *sql.DB }

// Do implements app.UnitOfWork.
func (u UnitOfWork) Do(ctx context.Context, fn func(ctx context.Context, tx app.Tx) error) error {
	t, err := u.DB.BeginTx(ctx, nil) // READ COMMITTED, the PostgreSQL default
	if err != nil {
		return err
	}
	if err := fn(ctx, txScope{q: t}); err != nil {
		_ = t.Rollback()
		return err
	}
	return t.Commit()
}

type txScope struct{ q querier }

func (s txScope) Orders() sales.OrderRepository { return Orders{Q: s.q} }
func (s txScope) Outbox() app.Outbox            { return Outbox{Q: s.q} }

// Orders is the OrderRepository adapter.
type Orders struct{ Q querier }

// Get loads the aggregate root and its lines.
func (r Orders) Get(ctx context.Context, id sales.OrderID) (*sales.Order, error) {
	var (
		customer, status, currency, payment string
		total                               int64
		placedAt                            time.Time
	)
	err := r.Q.QueryRowContext(ctx,
		`SELECT customer_id, status, total_minor, currency, payment_ref, placed_at
		   FROM sales_orders WHERE id = $1`, id).
		Scan(&customer, &status, &total, &currency, &payment, &placedAt)
	if errors.Is(err, sql.ErrNoRows) {
		return nil, sales.ErrOrderNotFound
	}
	if err != nil {
		return nil, err
	}
	rows, err := r.Q.QueryContext(ctx,
		`SELECT sku, quantity, unit_minor FROM sales_order_lines WHERE order_id = $1 ORDER BY position`, id)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var lines []sales.Line
	for rows.Next() {
		var l sales.Line
		var unit int64
		if err := rows.Scan(&l.SKU, &l.Quantity, &unit); err != nil {
			return nil, err
		}
		l.UnitPrice = sales.Money{Minor: unit, Currency: currency}
		lines = append(lines, l)
	}
	return sales.Rehydrate(id, sales.CustomerID(customer), lines, sales.Status(status),
		sales.Money{Minor: total, Currency: currency}, payment, placedAt), rows.Err()
}

// Add inserts a new aggregate. A primary-key violation (SQLSTATE 23505)
// becomes the domain error ErrDuplicateOrder.
func (r Orders) Add(ctx context.Context, o *sales.Order) error {
	_, err := r.Q.ExecContext(ctx,
		`INSERT INTO sales_orders (id, customer_id, status, total_minor, currency, payment_ref, placed_at)
		 VALUES ($1, $2, $3, $4, $5, $6, $7)`,
		o.ID(), o.Customer(), o.Status(), o.Total().Minor, o.Total().Currency, o.PaymentRef(), o.PlacedAt())
	if err != nil {
		if strings.Contains(err.Error(), "23505") {
			return sales.ErrDuplicateOrder
		}
		return fmt.Errorf("insert order: %w", err)
	}
	for i, l := range o.Lines() {
		if _, err := r.Q.ExecContext(ctx,
			`INSERT INTO sales_order_lines (order_id, position, sku, quantity, unit_minor) VALUES ($1, $2, $3, $4, $5)`,
			o.ID(), i, l.SKU, l.Quantity, l.UnitPrice.Minor); err != nil {
			return fmt.Errorf("insert line: %w", err)
		}
	}
	return nil
}

// Outbox writes events into the same transaction as the order.
type Outbox struct{ Q querier }

// publishedTypes maps a domain event's class name to the dotted, versioned
// type of the published language; only the outbox row carries the wire name.
var publishedTypes = map[string]string{
	"OrderPlaced": "sales.order.placed.v1",
}

// Append implements app.Outbox.
func (b Outbox) Append(ctx context.Context, events ...sales.Event) error {
	for _, e := range events {
		name, ok := publishedTypes[e.EventName()]
		if !ok {
			return fmt.Errorf("outbox: no published type for %s", e.EventName())
		}
		payload, err := json.Marshal(e)
		if err != nil {
			return err
		}
		if _, err := b.Q.ExecContext(ctx,
			`INSERT INTO outbox (event_name, payload) VALUES ($1, $2)`, name, payload); err != nil {
			return fmt.Errorf("outbox: %w", err)
		}
	}
	return nil
}
go
// Package stripe is an infrastructure adapter: it implements app.PaymentGateway
// over Stripe's HTTP API. Stripe vocabulary (PaymentIntent, capture_method,
// Idempotency-Key) stays in this package and never reaches the domain.
package stripe

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"strconv"
	"strings"

	"academy/domain-application-infrastructure-services/app"
	"academy/domain-application-infrastructure-services/sales"
)

// Gateway talks to Stripe (or to an httptest server in contract tests).
type Gateway struct {
	BaseURL string // https://api.stripe.com
	APIKey  string
	HTTP    *http.Client
}

type intent struct {
	ID    string `json:"id"`
	Error *struct {
		Type string `json:"type"`
		Code string `json:"code"`
	} `json:"error"`
}

// Authorize creates a PaymentIntent with capture_method=manual: the money is
// reserved now and captured when Fulfilment ships.
func (g Gateway) Authorize(ctx context.Context, key string, amount sales.Money, token string) (string, error) {
	form := url.Values{}
	form.Set("amount", strconv.FormatInt(amount.Minor, 10))
	form.Set("currency", strings.ToLower(amount.Currency))
	form.Set("payment_method", token)
	form.Set("capture_method", "manual")
	form.Set("confirm", "true")
	var in intent
	if err := g.post(ctx, "/v1/payment_intents", key, form, &in); err != nil {
		return "", err
	}
	return in.ID, nil
}

// Void cancels an uncaptured PaymentIntent.
func (g Gateway) Void(ctx context.Context, ref string) error {
	var in intent
	return g.post(ctx, "/v1/payment_intents/"+url.PathEscape(ref)+"/cancel", "void-"+ref, url.Values{}, &in)
}

func (g Gateway) post(ctx context.Context, path, idemKey string, form url.Values, out *intent) error {
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, g.BaseURL+path, strings.NewReader(form.Encode()))
	if err != nil {
		return err
	}
	req.Header.Set("Authorization", "Bearer "+g.APIKey)
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Idempotency-Key", idemKey) // a retry returns the first result
	resp, err := g.HTTP.Do(req)
	if err != nil {
		return fmt.Errorf("stripe: %w", err)
	}
	defer resp.Body.Close()
	if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
		return fmt.Errorf("stripe: decode: %w", err)
	}
	if resp.StatusCode == http.StatusPaymentRequired || (out.Error != nil && out.Error.Type == "card_error") {
		code := ""
		if out.Error != nil {
			code = out.Error.Code
		}
		return fmt.Errorf("stripe %s: %w", code, app.ErrPaymentDeclined)
	}
	if resp.StatusCode >= 300 {
		return fmt.Errorf("stripe: status %d", resp.StatusCode)
	}
	return nil
}
go
// Package httpapi is a driving (primary) adapter: it turns HTTP into a
// command DTO, calls the application service and maps errors to status codes.
package httpapi

import (
	"context"
	"encoding/json"
	"errors"
	"net/http"

	"academy/domain-application-infrastructure-services/app"
	"academy/domain-application-infrastructure-services/app/command"
	"academy/domain-application-infrastructure-services/app/decorator"
	"academy/domain-application-infrastructure-services/sales"
)

// PlaceOrderHandler is the only thing this adapter needs from the inside.
type PlaceOrderHandler interface {
	Handle(ctx context.Context, cmd command.PlaceOrder) (command.PlaceOrderResult, error)
}

type placeOrderBody struct {
	CustomerID   string `json:"customer_id"`
	PaymentToken string `json:"payment_token"`
	Items        []struct {
		SKU      string `json:"sku"`
		Quantity int    `json:"quantity"`
	} `json:"items"`
}

// PlaceOrder serves POST /orders. Shape validation happens here; business
// rules are checked by the domain and come back as domain errors.
func PlaceOrder(h PlaceOrderHandler) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		key := r.Header.Get("Idempotency-Key")
		if key == "" {
			http.Error(w, "Idempotency-Key header required", http.StatusPreconditionRequired) // 428
			return
		}
		var b placeOrderBody
		if err := json.NewDecoder(r.Body).Decode(&b); err != nil || b.CustomerID == "" || len(b.Items) == 0 {
			http.Error(w, "invalid request", http.StatusUnprocessableEntity)
			return
		}
		cmd := command.PlaceOrder{OrderID: sales.OrderID(key), CustomerID: sales.CustomerID(b.CustomerID), PaymentToken: b.PaymentToken}
		for _, it := range b.Items {
			cmd.Items = append(cmd.Items, command.Item{SKU: sales.SKU(it.SKU), Quantity: it.Quantity})
		}
		res, err := h.Handle(r.Context(), cmd)
		switch {
		case errors.Is(err, sales.ErrBadQuantity), errors.Is(err, sales.ErrEmptyOrder):
			http.Error(w, err.Error(), http.StatusUnprocessableEntity)
		case errors.Is(err, app.ErrPaymentDeclined):
			http.Error(w, err.Error(), http.StatusPaymentRequired)
		case errors.Is(err, context.DeadlineExceeded):
			http.Error(w, "timeout", http.StatusGatewayTimeout)
		case errors.Is(err, decorator.ErrForbidden):
			http.Error(w, err.Error(), http.StatusForbidden)
		case err != nil:
			http.Error(w, "internal error", http.StatusInternalServerError)
		default:
			status := http.StatusCreated
			if res.Replay {
				status = http.StatusOK
			}
			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(status)
			_ = json.NewEncoder(w).Encode(map[string]any{"order_id": res.OrderID, "total": res.Total.String()})
		}
	}
}

Composition root ​

go
// Command shop is the composition root: the ONE place that knows every
// concrete type and wires adapters into ports. Nothing else calls "new" on
// infrastructure.
package main

import (
	"database/sql"
	"log"
	"log/slog"
	"net/http"
	"os"
	"time"

	"academy/domain-application-infrastructure-services/adapters/clock"
	"academy/domain-application-infrastructure-services/adapters/httpapi"
	"academy/domain-application-infrastructure-services/adapters/memory"
	"academy/domain-application-infrastructure-services/adapters/postgres"
	"academy/domain-application-infrastructure-services/adapters/stripe"
	"academy/domain-application-infrastructure-services/app"
	"academy/domain-application-infrastructure-services/app/command"
	"academy/domain-application-infrastructure-services/app/decorator"
	"academy/domain-application-infrastructure-services/sales"
)

func main() {
	logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))

	// Driven adapters. With DATABASE_URL unset the in-memory store is used,
	// so the binary runs without Docker (a database/sql driver such as pgx's
	// stdlib package must be blank-imported for the Postgres branch).
	var (
		uow    app.UnitOfWork
		orders sales.OrderRepository
	)
	if dsn := os.Getenv("DATABASE_URL"); dsn != "" {
		db, err := sql.Open("pgx", dsn)
		if err != nil {
			log.Fatal(err)
		}
		uow, orders = postgres.UnitOfWork{DB: db}, postgres.Orders{Q: db}
	} else {
		mem := memory.NewStore()
		uow, orders = mem, mem
	}
	var payments app.PaymentGateway = memory.NewPayments()
	if key := os.Getenv("STRIPE_KEY"); key != "" {
		payments = stripe.Gateway{BaseURL: "https://api.stripe.com", APIKey: key, HTTP: &http.Client{Timeout: 10 * time.Second}}
	}

	// Application service with its domain service and ports.
	place := command.PlaceOrderHandler{
		UoW:        uow,
		Orders:     orders,
		Catalog:    memory.Catalog{"MUG": sales.EUR(1200), "TEA": sales.EUR(800)},
		Customers:  memory.Customers{"c-gold": sales.TierGold},
		Promotions: memory.Promotions{{Code: "MUG3", SKU: "MUG", MinQty: 3, PercentOff: 10}},
		Payments:   payments,
		Clock:      clock.System{},
		Pricing:    sales.PricingService{GoldPercentOff: 5, FreeShippingFrom: 5000, FlatShippingMinor: 495},
	}

	// Cross-cutting concerns as decorators, outermost first in reading order.
	var h decorator.Handler[command.PlaceOrder, command.PlaceOrderResult] = place
	h = decorator.Logging("PlaceOrder", logger, h)

	// Driving adapter.
	mux := http.NewServeMux()
	mux.Handle("POST /orders", httpapi.PlaceOrder(h))
	addr := ":8080"
	if a := os.Getenv("ADDR"); a != "" {
		addr = a
	}
	logger.Info("listening", "addr", addr)
	log.Fatal(http.ListenAndServe(addr, mux))
}

Tests: one style per kind of service ​

The domain service gets a pure table test, with no fakes:

go
package sales_test

import (
	"testing"

	"academy/domain-application-infrastructure-services/sales"
)

// A domain service is pure: no fakes, no database, no clock. Table tests only.
func TestPricingService_Quote(t *testing.T) {
	policy := sales.PricingService{GoldPercentOff: 5, FreeShippingFrom: 5000, FlatShippingMinor: 495}
	promo := sales.Promotion{Code: "MUG3", SKU: "MUG", MinQty: 3, PercentOff: 10}

	cases := []struct {
		name      string
		lines     []sales.Line
		tier      sales.Tier
		wantTotal int64
		wantShip  int64
	}{
		{"small standard order pays shipping", []sales.Line{{SKU: "MUG", Quantity: 1, UnitPrice: sales.EUR(1200)}}, sales.TierStandard, 1695, 495},
		{"promotion applies from 3 mugs", []sales.Line{{SKU: "MUG", Quantity: 3, UnitPrice: sales.EUR(1200)}}, sales.TierStandard, 3240 + 495, 495},
		{"gold on top of promotion, free shipping", []sales.Line{
			{SKU: "MUG", Quantity: 5, UnitPrice: sales.EUR(1200)},
			{SKU: "TEA", Quantity: 2, UnitPrice: sales.EUR(800)},
		}, sales.TierGold, 6650, 0},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			o, err := sales.NewOrder("o-1", "c-1", tc.lines)
			if err != nil {
				t.Fatal(err)
			}
			q, err := policy.Quote(o, tc.tier, []sales.Promotion{promo})
			if err != nil {
				t.Fatal(err)
			}
			if q.Total.Minor != tc.wantTotal || q.Shipping.Minor != tc.wantShip {
				t.Fatalf("total=%d shipping=%d, want %d and %d", q.Total.Minor, q.Shipping.Minor, tc.wantTotal, tc.wantShip)
			}
		})
	}
}

func TestPricingService_RejectsMixedCurrencies(t *testing.T) {
	o, _ := sales.NewOrder("o-2", "c-1", []sales.Line{
		{SKU: "MUG", Quantity: 1, UnitPrice: sales.EUR(1200)},
		{SKU: "TEA", Quantity: 1, UnitPrice: sales.Money{Minor: 900, Currency: "USD"}},
	})
	if _, err := (sales.PricingService{}).Quote(o, sales.TierStandard, nil); err == nil {
		t.Fatal("want currency mismatch error")
	}
}

The application service is tested with in-memory adapters. It checks orchestration: what was saved, what went to the outbox, what was charged and voided, and the duplicate race:

go
package command_test

import (
	"context"
	"errors"
	"testing"
	"time"

	"academy/domain-application-infrastructure-services/adapters/memory"
	"academy/domain-application-infrastructure-services/app/command"
	"academy/domain-application-infrastructure-services/sales"
)

// An application service is tested with in-memory adapters (fakes): we check
// orchestration (what was saved, which events, which side effects), not prices.
func newHandler() (command.PlaceOrderHandler, *memory.Store, *memory.Payments) {
	store, pay := memory.NewStore(), memory.NewPayments()
	return command.PlaceOrderHandler{
		UoW: store, Orders: store,
		Catalog:    memory.Catalog{"MUG": sales.EUR(1200)},
		Customers:  memory.Customers{},
		Promotions: memory.Promotions{},
		Payments:   pay,
		Clock:      memory.FixedClock{T: time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)},
		Pricing:    sales.PricingService{GoldPercentOff: 5, FreeShippingFrom: 5000, FlatShippingMinor: 495},
	}, store, pay
}

var cmd = command.PlaceOrder{OrderID: "o-1", CustomerID: "c-1", Items: []command.Item{{SKU: "MUG", Quantity: 1}}, PaymentToken: "pm"}

func TestPlaceOrder_SavesOrderAndOutboxesEvent(t *testing.T) {
	h, store, pay := newHandler()
	res, err := h.Handle(context.Background(), cmd)
	if err != nil {
		t.Fatal(err)
	}
	if res.Total.Minor != 1695 {
		t.Fatalf("total = %d", res.Total.Minor)
	}
	o, err := store.Get(context.Background(), "o-1")
	if err != nil || o.Status() != sales.Placed {
		t.Fatalf("order not placed: %v", err)
	}
	ev := store.Outboxed()
	if len(ev) != 1 || ev[0].EventName() != "OrderPlaced" {
		t.Fatalf("outbox = %v", ev)
	}
	if _, ok := pay.Authorized["order-o-1"]; !ok {
		t.Fatal("payment not authorized with the order idempotency key")
	}
}

func TestPlaceOrder_IsIdempotent(t *testing.T) {
	h, store, pay := newHandler()
	_, _ = h.Handle(context.Background(), cmd)
	res, err := h.Handle(context.Background(), cmd)
	if err != nil || !res.Replay {
		t.Fatalf("replay=%v err=%v", res.Replay, err)
	}
	if len(store.Outboxed()) != 1 || len(pay.Authorized) != 1 {
		t.Fatal("a replayed command must not publish or charge twice")
	}
}

func TestPlaceOrder_VoidsPaymentWhenCommitFails(t *testing.T) {
	h, store, pay := newHandler()
	store.FailCommit = errors.New("connection reset")
	if _, err := h.Handle(context.Background(), cmd); err == nil {
		t.Fatal("want error")
	}
	if len(pay.Voided) != 1 || len(store.Outboxed()) != 0 {
		t.Fatalf("voided=%v outbox=%v", pay.Voided, store.Outboxed())
	}
}

func TestPlaceOrder_DomainRuleComesBackUnchanged(t *testing.T) {
	h, _, pay := newHandler()
	bad := cmd
	bad.Items = []command.Item{{SKU: "MUG", Quantity: 99}}
	if _, err := h.Handle(context.Background(), bad); !errors.Is(err, sales.ErrBadQuantity) {
		t.Fatalf("err = %v", err)
	}
	if len(pay.Authorized) != 0 {
		t.Fatal("no payment may be attempted for an invalid order")
	}
}

// Two requests with the same OrderID race: both pass the idempotency read,
// the second loses on the primary key. It must NOT void the shared payment.
func TestPlaceOrder_LosingTheDuplicateRaceDoesNotVoid(t *testing.T) {
	h, store, pay := newHandler()
	winner, _ := sales.NewOrder("o-1", "c-1", []sales.Line{{SKU: "MUG", Quantity: 1, UnitPrice: sales.EUR(1200)}})
	q, _ := h.Pricing.Quote(winner, sales.TierStandard, nil)
	_ = winner.Place(q, "auth_order-o-1", time.Now())
	// The idempotency read sees nothing, then the winner commits before us.
	h.Orders = &racingRepo{OrderRepository: store, beforeFirstGet: func() { _ = store.Add(context.Background(), winner) }}

	res, err := h.Handle(context.Background(), cmd)
	if err != nil || !res.Replay {
		t.Fatalf("replay=%v err=%v", res.Replay, err)
	}
	if len(pay.Voided) != 0 {
		t.Fatalf("voided the winner's payment: %v", pay.Voided)
	}
}

// racingRepo reports "not found" on the first Get and lets the winner commit.
type racingRepo struct {
	sales.OrderRepository
	beforeFirstGet func()
}

func (r *racingRepo) Get(ctx context.Context, id sales.OrderID) (*sales.Order, error) {
	if r.beforeFirstGet != nil {
		r.beforeFirstGet()
		r.beforeFirstGet = nil
		return nil, sales.ErrOrderNotFound
	}
	return r.OrderRepository.Get(ctx, id)
}

The infrastructure adapter gets a contract test against an httptest.Server. It checks the wire format and the error translation, not the use case:

go
package stripe_test

import (
	"context"
	"errors"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"academy/domain-application-infrastructure-services/adapters/stripe"
	"academy/domain-application-infrastructure-services/app"
	"academy/domain-application-infrastructure-services/sales"
)

// An adapter is tested against the wire contract, not against the use case.
func TestGateway_AuthorizeSendsContract(t *testing.T) {
	var gotKey, gotBody string
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		gotKey = r.Header.Get("Idempotency-Key")
		b, _ := io.ReadAll(r.Body)
		gotBody = string(b)
		_, _ = io.WriteString(w, `{"id":"pi_123","status":"requires_capture"}`)
	}))
	defer srv.Close()

	g := stripe.Gateway{BaseURL: srv.URL, APIKey: "sk_test", HTTP: srv.Client()}
	ref, err := g.Authorize(context.Background(), "order-o-1", sales.EUR(1695), "pm_card_visa")
	if err != nil || ref != "pi_123" {
		t.Fatalf("ref=%q err=%v", ref, err)
	}
	if gotKey != "order-o-1" {
		t.Fatalf("Idempotency-Key = %q", gotKey)
	}
	for _, want := range []string{"amount=1695", "currency=eur", "capture_method=manual"} {
		if !strings.Contains(gotBody, want) {
			t.Fatalf("body %q lacks %q", gotBody, want)
		}
	}
}

func TestGateway_TranslatesCardError(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusPaymentRequired)
		_, _ = io.WriteString(w, `{"error":{"type":"card_error","code":"card_declined"}}`)
	}))
	defer srv.Close()
	g := stripe.Gateway{BaseURL: srv.URL, HTTP: srv.Client()}
	if _, err := g.Authorize(context.Background(), "k", sales.EUR(100), "pm"); !errors.Is(err, app.ErrPaymentDeclined) {
		t.Fatalf("err = %v, want ErrPaymentDeclined", err)
	}
}

The dependency rule as a test:

go
package sales_test

import (
	"go/parser"
	"go/token"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

// The dependency rule as a test: the domain imports no layer above it and no
// I/O package. Breaking the rule fails CI, not a code review.
func TestDomainImportsNothingOutward(t *testing.T) {
	forbidden := []string{"/app", "/adapters", "database/sql", "net/http", "log/slog", "os"}
	files, _ := filepath.Glob("*.go")
	for _, f := range files {
		if strings.HasSuffix(f, "_test.go") {
			continue
		}
		src, err := os.ReadFile(f)
		if err != nil {
			t.Fatal(err)
		}
		ast, err := parser.ParseFile(token.NewFileSet(), f, src, parser.ImportsOnly)
		if err != nil {
			t.Fatal(err)
		}
		for _, imp := range ast.Imports {
			path := strings.Trim(imp.Path.Value, `"`)
			for _, bad := range forbidden {
				if path == bad || strings.HasSuffix(path, bad) || strings.Contains(path, bad+"/") {
					t.Errorf("%s imports %s: the domain must not depend on it", f, path)
				}
			}
		}
	}
}

Wrong: the fat service ​

go
// Package wrong shows the shape this chapter argues against: one "service"
// that is controller, use case, pricing policy, SQL and payment client at once.
package wrong

import (
	"bytes"
	"context"
	"database/sql"
	"fmt"
	"net/http"
	"time"
)

// OrderService is a fat application service. Every rule below is a business
// rule living in the wrong layer, and every dependency is concrete.
type OrderService struct {
	DB *sql.DB
}

// Item is a requested line.
type Item struct {
	SKU      string
	Quantity int
}

// PlaceOrder mixes four kinds of code; see the comments.
func (s OrderService) PlaceOrder(ctx context.Context, customerID string, items []Item) (int64, error) {
	tx, err := s.DB.BeginTx(ctx, nil)
	if err != nil {
		return 0, err
	}
	defer tx.Rollback()

	var total int64
	for _, it := range items {
		var price int64
		// infrastructure inside the use case: raw SQL against another context's table
		if err := tx.QueryRowContext(ctx, `SELECT price_minor FROM catalog_products WHERE sku = $1`, it.SKU).Scan(&price); err != nil {
			return 0, err
		}
		line := price * int64(it.Quantity)
		if it.SKU == "MUG" && it.Quantity >= 3 { // pricing policy hard-coded in the service
			line = line * 90 / 100
		}
		total += line
	}
	var tier string
	_ = tx.QueryRowContext(ctx, `SELECT tier FROM identity_customers WHERE id = $1`, customerID).Scan(&tier)
	if tier == "gold" { // another business rule
		total = total * 95 / 100
	}
	if total < 5000 {
		total += 495
	}
	// I/O to a payment provider while the transaction holds locks and a connection
	body := fmt.Sprintf(`amount=%d&currency=eur&capture_method=manual`, total)
	resp, err := http.Post("https://api.stripe.com/v1/payment_intents", "application/x-www-form-urlencoded", bytes.NewBufferString(body))
	if err != nil {
		return 0, err
	}
	resp.Body.Close()

	var id int64
	err = tx.QueryRowContext(ctx,
		`INSERT INTO sales_orders (customer_id, status, total_minor, placed_at) VALUES ($1, 'placed', $2, $3) RETURNING id`,
		customerID, total, time.Now()). // hidden dependency on the wall clock
		Scan(&id)
	if err != nil {
		return 0, err
	}
	return id, tx.Commit() // no event: Fulfilment and Billing never hear about it
}

The Go angle ​

  • Interfaces belong to the consumer. Go's implicit interfaces make ports natural: app.PaymentGateway is declared where it is used, and stripe.Gateway satisfies it without importing anything. The Go Code Review Comments say the same: interfaces "generally belong in the package that uses values of the interface type".
  • Package layout is the architecture. sales importing nothing outward is checked by the compiler for cycles, and by deps_test.go for direction. Tools such as go-arch-lint or depguard (golangci-lint) do the same in CI (Project Layout & Linting).
  • Generic decorators. Since Go 1.18, decorator.Handler[C, R] lets one Logging wrap every handler. Wild Workouts uses the same idea with decorator.CommandHandler[C].
  • context.Context carries cancellation and the request's deadline from the HTTP adapter through the use case to database/sql and the Stripe client. It is not a bag for dependencies; ports are struct fields.
  • No DI container needed. main.go is the composition root. Use google/wire only when manual wiring stops fitting on a screen. Testing with fakes is covered in Mocking & DI in Go.

Laravel ​

The same use case in a Laravel 13 module (app/Modules/Sales/{Domain,Application,Infrastructure}), on PHP 8.4 syntax. PHP was reviewed, not run (no PHP on the authoring machine).

Domain: plain PHP, no Eloquent, no facades ​

php
<?php

namespace App\Modules\Sales\Domain;

use DateTimeImmutable;

/**
 * Aggregate root. A plain PHP class: no Eloquent, no facades, no now().
 * The repository maps it to tables; the application service drives it.
 */
final class Order
{
    private string $status = 'draft';

    private ?Money $total = null;

    private ?string $paymentRef = null;

    private ?DateTimeImmutable $placedAt = null;

    /** @var list<object> */
    private array $events = [];

    /** @param list<OrderLine> $lines */
    public function __construct(
        public readonly string $id,
        public readonly string $customerId,
        private readonly array $lines,
    ) {
        if ($lines === []) {
            throw new OrderRuleViolated('an order needs at least one line');
        }
    }

    /**
     * Rebuild a stored order without re-running place() or raising events.
     * Only repositories call this.
     *
     * @param  list<OrderLine>  $lines
     */
    public static function reconstitute(string $id, string $customerId, array $lines, string $status, ?Money $total, ?string $paymentRef, ?DateTimeImmutable $placedAt): self
    {
        $order = new self($id, $customerId, $lines);
        [$order->status, $order->total, $order->paymentRef, $order->placedAt] = [$status, $total, $paymentRef, $placedAt];

        return $order;
    }

    public function place(Quote $quote, string $paymentRef, DateTimeImmutable $now): void
    {
        if ($this->status !== 'draft') {
            throw new OrderRuleViolated('the order has already been placed');
        }
        if ($quote->orderId !== $this->id) {
            throw new OrderRuleViolated('the quote was made for another order');
        }

        [$this->status, $this->total, $this->paymentRef, $this->placedAt] = ['placed', $quote->total, $paymentRef, $now];
        $this->events[] = new OrderPlaced($this->id, $this->customerId, $quote->total, $paymentRef, $now);
    }

    /** @return list<object> recorded events, cleared on read */
    public function pullEvents(): array
    {
        [$events, $this->events] = [$this->events, []];

        return $events;
    }

    /** @return list<OrderLine> */
    public function lines(): array
    {
        return $this->lines;
    }

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

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

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

    public function placedAt(): ?DateTimeImmutable
    {
        return $this->placedAt;
    }
}
php
<?php

namespace App\Modules\Sales\Domain;

final readonly class OrderLine
{
    public function __construct(
        public string $sku,
        public int $quantity,
        public Money $unitPrice,
    ) {
        if ($quantity < 1 || $quantity > 50) {
            throw new OrderRuleViolated('quantity must be between 1 and 50');
        }
    }
}
php
<?php

namespace App\Modules\Sales\Domain;

use DateTimeImmutable;
use DateTimeInterface;
use JsonSerializable;

/** Domain event: a plain PHP object, no Laravel traits, no broadcasting. */
final readonly class OrderPlaced implements JsonSerializable
{
    public function __construct(
        public string $orderId,
        public string $customerId,
        public Money $total,
        public string $paymentRef,
        public DateTimeImmutable $placedAt,
    ) {}

    /** @return array<string, mixed> the published-language payload */
    public function jsonSerialize(): array
    {
        return [
            'order_id' => $this->orderId,
            'customer_id' => $this->customerId,
            'total_minor' => $this->total->minor,
            'currency' => $this->total->currency,
            'payment_ref' => $this->paymentRef,
            'placed_at' => $this->placedAt->format(DateTimeInterface::ATOM),
        ];
    }
}
php
<?php

namespace App\Modules\Sales\Domain;

/**
 * DOMAIN service. Pricing combines lines, the customer's tier and the active
 * promotions, so it belongs to no single entity. Stateless, no I/O, no
 * facades: the same input always gives the same Quote.
 */
final readonly class PricingService
{
    public function __construct(
        private int $goldPercentOff = 5,
        private int $freeShippingFromMinor = 5000,
        private int $flatShippingMinor = 495,
    ) {}

    /** @param list<Promotion> $promotions */
    public function quote(Order $order, CustomerTier $tier, array $promotions): Quote
    {
        $currency = $order->lines()[0]->unitPrice->currency;
        $subtotal = Money::zero($currency);
        $discount = Money::zero($currency);

        foreach ($order->lines() as $line) {
            $lineTotal = $line->unitPrice->times($line->quantity);
            $subtotal = $subtotal->add($lineTotal);

            $best = 0;
            foreach ($promotions as $promo) {
                if ($promo->sku === $line->sku && $line->quantity >= $promo->minQty) {
                    $best = max($best, $promo->percentOff);
                }
            }
            $discount = $discount->add($lineTotal->percentOff($best));
        }

        if ($tier === CustomerTier::Gold) {
            $discount = $discount->add($subtotal->sub($discount)->percentOff($this->goldPercentOff));
        }

        $net = $subtotal->sub($discount);
        $shipping = $net->minor >= $this->freeShippingFromMinor
            ? Money::zero($currency)
            : new Money($this->flatShippingMinor, $currency);

        return new Quote($order->id, $subtotal, $discount, $shipping, $net->add($shipping));
    }
}
php
<?php

namespace App\Modules\Sales\Domain;

/** Port owned by the domain; EloquentOrderRepository implements it. */
interface OrderRepository
{
    public function find(string $id): ?Order;

    /** @throws DuplicateOrder when the id is already taken */
    public function add(Order $order): void;
}

Application: ports, use case, query, decorator, job ​

php
<?php

namespace App\Modules\Sales\Application\Ports;

use App\Modules\Sales\Domain\Money;

/** Infrastructure-service port, in the use case's own words. */
interface PaymentGateway
{
    /** @throws PaymentDeclined */
    public function authorize(string $idempotencyKey, Money $amount, string $paymentToken): string;

    public function void(string $reference): void;
}
php
<?php

namespace App\Modules\Sales\Application\Ports;

interface UnitOfWork
{
    /**
     * Run $work in one transaction: commit on return, roll back on exception.
     *
     * @template T
     *
     * @param  callable(): T  $work
     * @return T
     */
    public function run(callable $work): mixed;
}
php
<?php

namespace App\Modules\Sales\Application;

/** Input DTO (command). Built by the Form Request, a job or a console command. */
final readonly class PlaceOrder
{
    /** @param list<array{sku: string, quantity: int}> $items */
    public function __construct(
        public string $orderId,
        public string $customerId,
        public array $items,
        public string $paymentToken,
    ) {}
}
php
<?php

namespace App\Modules\Sales\Application;

use App\Modules\Sales\Application\Ports\Catalog;
use App\Modules\Sales\Application\Ports\Clock;
use App\Modules\Sales\Application\Ports\Customers;
use App\Modules\Sales\Application\Ports\Outbox;
use App\Modules\Sales\Application\Ports\PaymentGateway;
use App\Modules\Sales\Application\Ports\Promotions;
use App\Modules\Sales\Application\Ports\UnitOfWork;
use App\Modules\Sales\Domain\DuplicateOrder;
use App\Modules\Sales\Domain\Order;
use App\Modules\Sales\Domain\OrderLine;
use App\Modules\Sales\Domain\OrderRepository;
use App\Modules\Sales\Domain\OrderRuleViolated;
use App\Modules\Sales\Domain\PricingService;
use Throwable;

/**
 * APPLICATION service (use case). It orchestrates: read inputs through
 * ports, let the domain decide, call the payment port outside the
 * transaction, save aggregate + events in one transaction. No pricing rule,
 * no SQL, no HTTP and no facade appears here.
 */
final readonly class PlaceOrderHandler implements PlacesOrders
{
    public function __construct(
        private OrderRepository $orders,
        private UnitOfWork $uow,
        private Outbox $outbox,
        private Catalog $catalog,
        private Customers $customers,
        private Promotions $promotions,
        private PaymentGateway $payments,
        private Clock $clock,
        private PricingService $pricing,
    ) {}

    public function handle(PlaceOrder $command): PlaceOrderResult
    {
        // 1. Idempotency: a repeated command returns the first result.
        if ($existing = $this->orders->find($command->orderId)) {
            return new PlaceOrderResult($existing->id, $existing->total(), replay: true);
        }

        // 2. Inputs through ports.
        $prices = $this->catalog->unitPrices(array_column($command->items, 'sku'));
        $lines = [];
        foreach ($command->items as $item) {
            $price = $prices[$item['sku']] ?? throw new OrderRuleViolated("unknown sku {$item['sku']}");
            $lines[] = new OrderLine($item['sku'], $item['quantity'], $price);
        }
        $now = $this->clock->now();

        // 3. Domain decides.
        $order = new Order($command->orderId, $command->customerId, $lines);
        $quote = $this->pricing->quote(
            $order,
            $this->customers->tierOf($command->customerId),
            $this->promotions->activeAt($now),
        );

        // 4. External side effect outside the DB transaction.
        $ref = $this->payments->authorize("order-{$order->id}", $quote->total, $command->paymentToken);

        try {
            $order->place($quote, $ref, $now);

            // 5. One transaction: aggregate + outbox rows.
            $this->uow->run(function () use ($order): void {
                $this->orders->add($order);
                $this->outbox->append(...$order->pullEvents());
            });
        } catch (DuplicateOrder) {
            // A concurrent request with the same id won the race. Both used the
            // same idempotency key, so they share ONE authorization: voiding it
            // would cancel the winner's payment. Return the winner's result.
            $winner = $this->orders->find($command->orderId);

            return new PlaceOrderResult($winner->id, $winner->total(), replay: true);
        } catch (Throwable $e) {
            $this->payments->void($ref); // compensate what SQL cannot roll back
            throw $e;
        }

        return new PlaceOrderResult($order->id, $quote->total);
    }
}
php
<?php

namespace App\Modules\Sales\Application\Queries;

/**
 * Query handler (CQS on the read side): no aggregate, no repository, no
 * transaction, no events. It returns DTO arrays shaped for the screen.
 */
final readonly class CustomerOrdersHandler
{
    public function __construct(private OrderSummaries $readModel) {}

    public function handle(CustomerOrders $query): array
    {
        return $this->readModel->forCustomer($query->customerId, min(max($query->limit, 1), 100));
    }
}
php
<?php

namespace App\Modules\Sales\Application\Middleware;

use App\Modules\Sales\Application\PlaceOrder;
use App\Modules\Sales\Application\PlaceOrderResult;
use App\Modules\Sales\Application\PlacesOrders;
use Psr\Log\LoggerInterface;
use Throwable;

/**
 * Decorator: logging and timing around the use case, registered with
 * $this->app->extend(). The correlation id comes from Laravel Context,
 * which appends it to every log entry automatically.
 */
final readonly class LogsPlaceOrder implements PlacesOrders
{
    public function __construct(private PlacesOrders $inner, private LoggerInterface $log) {}

    public function handle(PlaceOrder $command): PlaceOrderResult
    {
        $start = hrtime(true);
        try {
            $result = $this->inner->handle($command);
            $this->log->info('command handled', ['command' => 'PlaceOrder', 'ok' => true, 'ms' => (hrtime(true) - $start) / 1e6]);

            return $result;
        } catch (Throwable $e) {
            $this->log->warning('command failed', ['command' => 'PlaceOrder', 'error' => $e::class]);
            throw $e;
        }
    }
}

A queued job is another driving adapter. It calls the same use case later, on a worker:

php
<?php

namespace App\Modules\Sales\Application\Jobs;

use App\Modules\Sales\Application\PlaceOrder;
use App\Modules\Sales\Application\PlacesOrders;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

/**
 * A queued job is another DRIVING adapter: it carries the same command DTO
 * and calls the same use case, just later and on a worker (B2B CSV imports).
 * Retrying is safe because PlaceOrder is idempotent on orderId.
 */
final class PlaceOrderInBackground implements ShouldQueue
{
    use Queueable;

    public int $tries = 5;

    public function __construct(public PlaceOrder $command) {}

    public function handle(PlacesOrders $useCase): void
    {
        $useCase->handle($this->command);
    }

    /** @return list<int> */
    public function backoff(): array
    {
        return [5, 30, 120];
    }
}

Edge: Form Request, controller, correlation id ​

php
<?php

namespace App\Http\Requests;

use App\Modules\Sales\Application\PlaceOrder;
use Illuminate\Foundation\Http\FormRequest;

/**
 * The edge: authorization and SHAPE validation. Business rules (max quantity,
 * pricing, "already placed") stay in the domain; this class only refuses
 * requests that are not even well-formed.
 */
class PlaceOrderRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->can('place-orders') ?? false;
    }

    /** @return array<string, mixed> */
    public function rules(): array
    {
        return [
            'items' => ['required', 'array', 'min:1'],
            'items.*.sku' => ['required', 'string', 'max:64'],
            'items.*.quantity' => ['required', 'integer', 'min:1'],
            'payment_token' => ['required', 'string'],
        ];
    }

    public function toCommand(): PlaceOrder
    {
        return new PlaceOrder(
            orderId: (string) $this->header('Idempotency-Key'),
            customerId: (string) $this->user()->getAuthIdentifier(),
            items: array_map(
                fn (array $i) => ['sku' => $i['sku'], 'quantity' => (int) $i['quantity']],
                $this->validated('items'),
            ),
            paymentToken: $this->validated('payment_token'),
        );
    }
}
php
<?php

namespace App\Http\Controllers;

use App\Http\Requests\PlaceOrderRequest;
use App\Modules\Sales\Application\PlacesOrders;
use App\Modules\Sales\Application\Ports\PaymentDeclined;
use App\Modules\Sales\Domain\OrderRuleViolated;
use Illuminate\Http\JsonResponse;

/** Driving adapter: HTTP in, command DTO to the use case, HTTP out. */
class PlaceOrderController
{
    public function __invoke(PlaceOrderRequest $request, PlacesOrders $useCase): JsonResponse
    {
        abort_unless($request->hasHeader('Idempotency-Key'), 428, 'Idempotency-Key header required');

        try {
            $result = $useCase->handle($request->toCommand());
        } catch (OrderRuleViolated $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        } catch (PaymentDeclined $e) {
            return response()->json(['message' => 'payment declined'], 402);
        }

        return response()->json([
            'order_id' => $result->orderId,
            'total_minor' => $result->total->minor,
            'currency' => $result->total->currency,
        ], $result->replay ? 200 : 201);
    }
}
php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;

/**
 * Cross-cutting concern at the edge. Context data is appended to every log
 * entry and travels with queued jobs dispatched during this request.
 */
class AssignCorrelationId
{
    public function handle(Request $request, Closure $next): Response
    {
        Context::add('correlation_id', $request->header('X-Correlation-Id') ?? (string) Str::uuid());

        return $next($request);
    }
}

Infrastructure: Eloquent, unit of work, outbox, Stripe, clock ​

php
<?php

namespace App\Modules\Sales\Infrastructure;

use App\Modules\Sales\Domain\DuplicateOrder;
use App\Modules\Sales\Domain\Money;
use App\Modules\Sales\Domain\Order;
use App\Modules\Sales\Domain\OrderLine;
use App\Modules\Sales\Domain\OrderRepository;
use Illuminate\Database\UniqueConstraintViolationException;

/** Adapter: maps the aggregate to two tables with Eloquent. */
final class EloquentOrderRepository implements OrderRepository
{
    public function find(string $id): ?Order
    {
        $row = OrderRecord::with('lines')->find($id);
        if ($row === null) {
            return null;
        }

        $lines = $row->lines
            ->map(fn (OrderLineRecord $l) => new OrderLine($l->sku, $l->quantity, new Money($l->unit_minor, $row->currency)))
            ->all();

        return Order::reconstitute(
            $row->id,
            $row->customer_id,
            $lines,
            $row->status,
            $row->total_minor === null ? null : new Money($row->total_minor, $row->currency),
            $row->payment_ref,
            $row->placed_at,
        );
    }

    public function add(Order $order): void
    {
        try {
            $this->insert($order);
        } catch (UniqueConstraintViolationException) {
            throw new DuplicateOrder($order->id); // SQLSTATE 23505 / MySQL 1062
        }
    }

    private function insert(Order $order): void
    {
        OrderRecord::create([
            'id' => $order->id,
            'customer_id' => $order->customerId,
            'status' => $order->status(),
            'total_minor' => $order->total()?->minor,
            'currency' => $order->total()?->currency,
            'payment_ref' => $order->paymentRef(),
            'placed_at' => $order->placedAt(),
        ]);
        foreach ($order->lines() as $i => $line) {
            OrderLineRecord::create([
                'order_id' => $order->id,
                'position' => $i,
                'sku' => $line->sku,
                'quantity' => $line->quantity,
                'unit_minor' => $line->unitPrice->minor,
            ]);
        }
    }
}
php
<?php

namespace App\Modules\Sales\Infrastructure;

use App\Modules\Sales\Application\Ports\UnitOfWork;
use Illuminate\Database\ConnectionInterface;

final readonly class DatabaseUnitOfWork implements UnitOfWork
{
    public function __construct(private ConnectionInterface $db) {}

    public function run(callable $work): mixed
    {
        // Same as DB::transaction(): commit on return, roll back on exception.
        return $this->db->transaction(fn () => $work());
    }
}
php
<?php

namespace App\Modules\Sales\Infrastructure;

use App\Modules\Sales\Application\Ports\Outbox;
use App\Modules\Sales\Domain\OrderPlaced;
use Illuminate\Database\ConnectionInterface;

/** Writes integration-ready rows; a relay job publishes them after commit. */
final readonly class DatabaseOutbox implements Outbox
{
    public function __construct(private ConnectionInterface $db) {}

    public function append(object ...$events): void
    {
        foreach ($events as $event) {
            $this->db->table('outbox')->insert([
                'event_name' => match ($event::class) {
                    OrderPlaced::class => 'sales.order.placed.v1',
                    default => $event::class,
                },
                'payload' => json_encode($event, JSON_THROW_ON_ERROR),
                'created_at' => now(),
            ]);
        }
    }
}
php
<?php

namespace App\Modules\Sales\Infrastructure;

use App\Modules\Sales\Application\Ports\PaymentDeclined;
use App\Modules\Sales\Application\Ports\PaymentGateway;
use App\Modules\Sales\Domain\Money;
use Illuminate\Support\Facades\Http;

/**
 * Infrastructure service: Stripe's vocabulary (PaymentIntent, capture_method,
 * Idempotency-Key) stays in this class. Facades are fine HERE.
 */
final readonly class StripePaymentGateway implements PaymentGateway
{
    public function __construct(private string $secret, private string $baseUrl = 'https://api.stripe.com') {}

    public function authorize(string $idempotencyKey, Money $amount, string $paymentToken): string
    {
        $response = Http::withToken($this->secret)
            ->withHeaders(['Idempotency-Key' => $idempotencyKey])
            ->asForm()
            ->timeout(10)
            ->post("{$this->baseUrl}/v1/payment_intents", [
                'amount' => $amount->minor,
                'currency' => strtolower($amount->currency),
                'payment_method' => $paymentToken,
                'capture_method' => 'manual',
                'confirm' => 'true',
            ]);

        if ($response->status() === 402 || $response->json('error.type') === 'card_error') {
            throw new PaymentDeclined($response->json('error.code') ?? 'declined');
        }
        $response->throw();

        return $response->json('id');
    }

    public function void(string $reference): void
    {
        Http::withToken($this->secret)
            ->withHeaders(['Idempotency-Key' => "void-{$reference}"])
            ->asForm()
            ->post("{$this->baseUrl}/v1/payment_intents/{$reference}/cancel")
            ->throw();
    }
}
php
<?php

namespace App\Modules\Sales\Infrastructure;

use App\Modules\Sales\Application\Ports\Clock;
use DateTimeImmutable;
use Illuminate\Support\Facades\Date;

final class SystemClock implements Clock
{
    public function now(): DateTimeImmutable
    {
        // Date::now() honours Carbon test helpers such as $this->travelTo().
        return Date::now()->toDateTimeImmutable();
    }
}

Wiring: the service provider is the composition root ​

php
<?php

namespace App\Providers;

use App\Modules\Sales\Application\Middleware\LogsPlaceOrder;
use App\Modules\Sales\Application\PlaceOrderHandler;
use App\Modules\Sales\Application\PlacesOrders;
use App\Modules\Sales\Application\Ports\Catalog;
use App\Modules\Sales\Application\Ports\Clock;
use App\Modules\Sales\Application\Ports\Customers;
use App\Modules\Sales\Application\Ports\Outbox;
use App\Modules\Sales\Application\Ports\PaymentGateway;
use App\Modules\Sales\Application\Ports\Promotions;
use App\Modules\Sales\Application\Ports\UnitOfWork;
use App\Modules\Sales\Application\Queries\OrderSummaries;
use App\Modules\Sales\Domain\OrderRepository;
use App\Modules\Sales\Domain\PricingService;
use App\Modules\Sales\Infrastructure\DatabaseOrderSummaries;
use App\Modules\Sales\Infrastructure\DatabaseOutbox;
use App\Modules\Sales\Infrastructure\DatabasePricingInputs;
use App\Modules\Sales\Infrastructure\DatabaseUnitOfWork;
use App\Modules\Sales\Infrastructure\EloquentOrderRepository;
use App\Modules\Sales\Infrastructure\StripePaymentGateway;
use App\Modules\Sales\Infrastructure\SystemClock;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use Psr\Log\LoggerInterface;

/** Composition root for the Sales module: ports -> adapters. */
class SalesServiceProvider extends ServiceProvider
{
    /** Simple port => adapter bindings. */
    public array $bindings = [
        OrderRepository::class => EloquentOrderRepository::class,
        UnitOfWork::class => DatabaseUnitOfWork::class,
        Outbox::class => DatabaseOutbox::class,
        Clock::class => SystemClock::class,
        Catalog::class => DatabasePricingInputs::class,
        Customers::class => DatabasePricingInputs::class,
        Promotions::class => DatabasePricingInputs::class,
        PlacesOrders::class => PlaceOrderHandler::class,
        OrderSummaries::class => DatabaseOrderSummaries::class,
    ];

    public function register(): void
    {
        $this->app->singleton(PricingService::class, fn () => new PricingService(
            goldPercentOff: config('sales.gold_percent_off', 5),
            freeShippingFromMinor: config('sales.free_shipping_from_minor', 5000),
            flatShippingMinor: config('sales.flat_shipping_minor', 495),
        ));

        $this->app->singleton(PaymentGateway::class, fn () => new StripePaymentGateway(
            secret: (string) config('services.stripe.secret'),
        ));

        // Cross-cutting concern as a decorator around the use case.
        $this->app->extend(PlacesOrders::class, fn (PlacesOrders $useCase, Application $app) => new LogsPlaceOrder($useCase, $app->make(LoggerInterface::class)));
    }
}

Tests ​

The domain service runs as a plain PHPUnit TestCase, with no Laravel application booted:

php
<?php

namespace Tests\Unit;

use App\Modules\Sales\Domain\CustomerTier;
use App\Modules\Sales\Domain\Money;
use App\Modules\Sales\Domain\Order;
use App\Modules\Sales\Domain\OrderLine;
use App\Modules\Sales\Domain\PricingService;
use App\Modules\Sales\Domain\Promotion;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;

/** Pure unit test: plain PHPUnit TestCase, no Laravel app, no database. */
final class PricingServiceTest extends TestCase
{
    public static function cases(): array
    {
        $mug = fn (int $q) => new OrderLine('MUG', $q, Money::eur(1200));

        return [
            'small standard order pays shipping' => [[$mug(1)], CustomerTier::Standard, 1695],
            'promotion from 3 mugs' => [[$mug(3)], CustomerTier::Standard, 3240 + 495],
            'gold on top of promotion, free shipping' => [[$mug(5), new OrderLine('TEA', 2, Money::eur(800))], CustomerTier::Gold, 6650],
        ];
    }

    #[DataProvider('cases')]
    public function test_quote(array $lines, CustomerTier $tier, int $expectedTotal): void
    {
        $order = new Order('o-1', 'c-1', $lines);
        $quote = (new PricingService)->quote($order, $tier, [new Promotion('MUG3', 'MUG', 3, 10)]);

        $this->assertSame($expectedTotal, $quote->total->minor);
    }
}

The application service uses anonymous-class fakes and checks orchestration, idempotency, compensation and the duplicate race:

php
<?php

namespace Tests\Unit;

use App\Modules\Sales\Application\PlaceOrder;
use App\Modules\Sales\Application\PlaceOrderHandler;
use App\Modules\Sales\Application\Ports\Catalog;
use App\Modules\Sales\Application\Ports\Clock;
use App\Modules\Sales\Application\Ports\Customers;
use App\Modules\Sales\Application\Ports\Outbox;
use App\Modules\Sales\Application\Ports\PaymentGateway;
use App\Modules\Sales\Application\Ports\Promotions;
use App\Modules\Sales\Application\Ports\UnitOfWork;
use App\Modules\Sales\Domain\CustomerTier;
use App\Modules\Sales\Domain\DuplicateOrder;
use App\Modules\Sales\Domain\Money;
use App\Modules\Sales\Domain\Order;
use App\Modules\Sales\Domain\OrderLine;
use App\Modules\Sales\Domain\OrderPlaced;
use App\Modules\Sales\Domain\OrderRepository;
use App\Modules\Sales\Domain\OrderRuleViolated;
use App\Modules\Sales\Domain\PricingService;
use DateTimeImmutable;
use PHPUnit\Framework\TestCase;
use RuntimeException;

/** Application service with fakes: we assert orchestration, not prices. */
final class PlaceOrderHandlerTest extends TestCase
{
    private object $orders;

    private object $outbox;

    private object $payments;

    private object $uow;

    protected function setUp(): void
    {
        $this->orders = new class implements OrderRepository
        {
            public array $saved = [];

            public ?Order $racer = null; // simulates a concurrent winner

            public function find(string $id): ?Order
            {
                return $this->saved[$id] ?? null;
            }

            public function add(Order $order): void
            {
                if ($this->racer !== null) {
                    $this->saved[$this->racer->id] = $this->racer;
                    throw new DuplicateOrder($order->id);
                }
                $this->saved[$order->id] = $order;
            }
        };
        $this->outbox = new class implements Outbox
        {
            public array $events = [];

            public function append(object ...$events): void
            {
                array_push($this->events, ...$events);
            }
        };
        $this->payments = new class implements PaymentGateway
        {
            public array $authorized = [];

            public array $voided = [];

            public function authorize(string $idempotencyKey, Money $amount, string $paymentToken): string
            {
                $this->authorized[$idempotencyKey] = $amount;

                return "pi_{$idempotencyKey}";
            }

            public function void(string $reference): void
            {
                $this->voided[] = $reference;
            }
        };
        $this->uow = new class implements UnitOfWork
        {
            public bool $fail = false;

            public function run(callable $work): mixed
            {
                $result = $work();
                if ($this->fail) {
                    throw new RuntimeException('commit failed');
                }

                return $result;
            }
        };
    }

    private function handler(): PlaceOrderHandler
    {
        $inputs = new class implements Catalog, Customers, Promotions
        {
            public function unitPrices(array $skus): array
            {
                return ['MUG' => Money::eur(1200)];
            }

            public function tierOf(string $customerId): CustomerTier
            {
                return CustomerTier::Standard;
            }

            public function activeAt(DateTimeImmutable $at): array
            {
                return [];
            }
        };
        $clock = new class implements Clock
        {
            public function now(): DateTimeImmutable
            {
                return new DateTimeImmutable('2026-11-25T10:00:00Z');
            }
        };

        return new PlaceOrderHandler($this->orders, $this->uow, $this->outbox, $inputs, $inputs, $inputs, $this->payments, $clock, new PricingService);
    }

    private function command(int $quantity = 1): PlaceOrder
    {
        return new PlaceOrder('o-1', 'c-1', [['sku' => 'MUG', 'quantity' => $quantity]], 'pm_card_visa');
    }

    public function test_places_order_and_outboxes_event(): void
    {
        $result = $this->handler()->handle($this->command());

        $this->assertSame(1695, $result->total->minor);
        $this->assertSame('placed', $this->orders->saved['o-1']->status());
        $this->assertInstanceOf(OrderPlaced::class, $this->outbox->events[0]);
        $this->assertArrayHasKey('order-o-1', $this->payments->authorized);
    }

    public function test_is_idempotent(): void
    {
        $this->handler()->handle($this->command());
        $again = $this->handler()->handle($this->command());

        $this->assertTrue($again->replay);
        $this->assertCount(1, $this->outbox->events);
        $this->assertCount(1, $this->payments->authorized);
    }

    public function test_voids_payment_when_commit_fails(): void
    {
        $this->uow->fail = true;

        try {
            $this->handler()->handle($this->command());
            $this->fail('expected exception');
        } catch (RuntimeException) {
            $this->assertSame(['pi_order-o-1'], $this->payments->voided);
        }
    }

    public function test_domain_rule_is_not_charged(): void
    {
        $this->expectException(OrderRuleViolated::class);

        try {
            $this->handler()->handle($this->command(quantity: 99));
        } finally {
            $this->assertSame([], $this->payments->authorized);
        }
    }

    public function test_losing_the_duplicate_race_does_not_void(): void
    {
        $winner = new Order('o-1', 'c-1', [new OrderLine('MUG', 1, Money::eur(1200))]);
        $winner->place((new PricingService)->quote($winner, CustomerTier::Standard, []), 'pi_order-o-1', new DateTimeImmutable);
        $this->orders->racer = $winner;

        $result = $this->handler()->handle($this->command());

        $this->assertTrue($result->replay);
        $this->assertSame([], $this->payments->voided);
    }
}

The adapter's contract is checked with Http::fake() and Http::assertSent():

php
<?php

namespace Tests\Integration;

use App\Modules\Sales\Application\Ports\PaymentDeclined;
use App\Modules\Sales\Domain\Money;
use App\Modules\Sales\Infrastructure\StripePaymentGateway;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

/** Adapter test: the wire contract with Stripe, faked at the HTTP level. */
final class StripePaymentGatewayTest extends TestCase
{
    public function test_authorize_sends_idempotency_key_and_manual_capture(): void
    {
        Http::fake(['api.stripe.com/*' => Http::response(['id' => 'pi_123', 'status' => 'requires_capture'])]);

        $ref = (new StripePaymentGateway('sk_test'))->authorize('order-o-1', Money::eur(1695), 'pm_card_visa');

        $this->assertSame('pi_123', $ref);
        Http::assertSent(fn (Request $r) => $r->hasHeader('Idempotency-Key', 'order-o-1')
            && (int) $r['amount'] === 1695
            && $r['capture_method'] === 'manual');
    }

    public function test_card_error_becomes_payment_declined(): void
    {
        Http::fake(['api.stripe.com/*' => Http::response(['error' => ['type' => 'card_error', 'code' => 'card_declined']], 402)]);

        $this->expectException(PaymentDeclined::class);
        (new StripePaymentGateway('sk_test'))->authorize('k', Money::eur(100), 'pm');
    }
}

Wrong: controller as service, model with facades ​

php
<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;

/**
 * The fat "service" in controller form: validation, pricing policy, SQL into
 * other contexts' tables, a payment call inside a DB transaction, and a
 * hidden clock. Every rule is untestable without a database and Stripe.
 */
class OrderController
{
    public function store(Request $request)
    {
        return DB::transaction(function () use ($request) {
            $total = 0;
            foreach ($request->input('items') as $item) {
                $price = DB::table('catalog_products')->where('sku', $item['sku'])->value('price_minor');
                $line = $price * $item['quantity'];
                if ($item['sku'] === 'MUG' && $item['quantity'] >= 3) {
                    $line = intdiv($line * 90, 100); // pricing rule in a controller
                }
                $total += $line;
            }
            if ($request->user()->tier === 'gold') { // Identity's column read directly
                $total = intdiv($total * 95, 100);
            }
            $total += $total < 5000 ? 495 : 0;

            // network call while the transaction holds a connection and locks
            $intent = Http::withToken(config('services.stripe.secret'))->asForm()
                ->post('https://api.stripe.com/v1/payment_intents', ['amount' => $total, 'currency' => 'eur'])
                ->json();

            $order = Order::create([
                'customer_id' => $request->user()->id,
                'total_minor' => $total,
                'payment_ref' => $intent['id'],
                'placed_at' => now(), // hidden clock
            ]);

            return response()->json($order, 201); // no event: Billing and Fulfilment never hear
        });
    }
}
php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;

/**
 * Infrastructure leaking into the domain: a model whose "business method"
 * reaches for static facades. It cannot run without a database, a cache and
 * a mailer, so its rule cannot be unit-tested.
 */
class Order extends Model
{
    protected $guarded = [];

    public function applyLoyaltyDiscount(): void
    {
        $tier = Cache::remember("tier:{$this->customer_id}", 60, fn () => DB::table('identity_customers')->where('id', $this->customer_id)->value('tier'));
        if ($tier === 'gold') {
            $this->total_minor = intdiv($this->total_minor * 95, 100);
            $this->save();
            Mail::raw('You saved 5%!', fn ($m) => $m->to($this->customer_email));
        }
    }
}

The Laravel angle ​

  • Mapping. Form Request (edge: authorize() + rules()) → command DTO → use case or Action class (application) → domain objects (plain PHP) → repository port → Eloquent adapter → outbox or ShouldDispatchAfterCommit events. Eloquent models live in Infrastructure as persistence records. Where a module is plain CRUD, using Eloquent directly in the use case is a legitimate choice, but it is a choice you make on purpose (Anemic vs Rich).
  • The container is the composition root. The $bindings property maps ports to adapters. singleton builds configured objects. extend adds decorators. The docs describe extend as a way to "decorate or configure the service".
  • Jobs are asynchronous application services, or better, asynchronous driving adapters. A ShouldQueue job should carry a command DTO and call the same use case. It should not contain a second copy of the flow. Mark retried jobs idempotent, and dispatch with ->afterCommit() when they are created inside a transaction.
  • Facades are an infrastructure convenience. DB::, Http::, Cache::, Mail:: and now() are fine in adapters, controllers and providers. In domain classes they hide dependencies and make rules untestable without the framework. Date::now() in SystemClock keeps travelTo() working in tests.
  • Context for correlation. Context::add('correlation_id', ...) in middleware puts the id into every log line and into queued jobs dispatched during the request. Decorators then log without passing ids around.
  • Transactions. DB::transaction(fn, attempts) (or ConnectionInterface::transaction) behind a UnitOfWork port keeps the facade out of the use case. Its second argument retries the closure "when a deadlock occurs".

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Fat application servicePush rules downEach if about the business becomes an entity method or a domain serviceRules unit-testable, reused by every entry pointRefactoring time; rich model needed
Domain service as a dumping groundSplit by operation, return rules to entitiesOne service per named operation; entity-local rules move backCohesion, smaller testsNeeds domain knowledge to name
"Service" on everythingName by ubiquitous languageVerbs for use cases, technology for adaptersCode reads like the businessRenames touch many files
Eloquent / DB in the domainRepository port + adapterDomain interface, Eloquent model in InfrastructureDomain runs without a databaseMapping code
Static facades in the modelPass values or inject portsnow as argument; Clock port in the use caseDeterministic testsMore constructor parameters
External call inside transactionCall outside, compensateAuthorize → commit → void on failure; idempotency keyNo locks held on network I/OCompensation logic; duplicate race to handle
Events dispatched before commitOutbox or after-commit dispatchOutbox row in the same tx; ShouldDispatchAfterCommitNo phantom eventsRelay process; at-least-once delivery
Same flow copied into controller, job and CLIOne use case, many driving adaptersController, job and command build the same DTOOne place to changeDTO mapping per adapter

The fat application service ​

The wrong Go service and the wrong controller hold four kinds of code in one function: SQL against two foreign tables, a hard-coded promotion, a loyalty discount, a Stripe call inside the transaction, and the wall clock. The refactoring is mechanical:

  1. Extract the rules (>= 3 mugs, gold, < 5000) into PricingService and write the table test first. It pins today's behaviour.
  2. Replace the SQL into catalog_products and identity_customers with the Catalog and Customers ports. Implement them over local read models, not other modules' tables (Data Ownership).
  3. Move the Stripe call out of the transaction behind PaymentGateway, with an idempotency key and a void on failure.
  4. Replace time.Now() / now() with the Clock port and pass now into the domain.
  5. Record OrderPlaced in the aggregate and append it to the outbox in the same transaction.

The domain service as a dumping ground ​

The symptom is OrderDomainService with calculateTotal, canCancel, isEditable, formatForEmail, exportCsv. Ask of each method: does it need more than one aggregate or value object? canCancel and isEditable need only the order, so they move onto Order. formatForEmail is presentation and moves to the mail adapter. exportCsv is a query handler. Only calculateTotal, which needs promotions and the tier, survives, renamed PricingService.Quote.

The "Service" suffix everywhere ​

Rename by role: use cases as verbs (PlaceOrder), domain services after the business concept (PricingService, FundsTransfer), adapters after the technology (StripePaymentGateway), ports after the capability (PaymentGateway, Clock). When a name will not come, the class probably does more than one thing.

Infrastructure leaking into the domain via Eloquent or DB ​

An Eloquent model is an active record: it knows its table and connection. Using it as the domain object is a valid choice for CRUD modules, but then the domain cannot be tested or reasoned about without a database. In a core module, keep the domain as plain PHP. Map it to and from OrderRecord in EloquentOrderRepository, and turn UniqueConstraintViolationException into the domain's DuplicateOrder there. Repositories covers the mapping in depth.

Static facades in the domain layer ​

The wrong Order model calls Cache::remember, DB::table and Mail::raw inside applyLoyaltyDiscount(). The rule ("gold gets 5%") is three lines. The rest is infrastructure, and it makes those three lines untestable without a cache, a database and a mailer. The fix is the same as for the fat service: the tier arrives as an argument, the discount is computed in PricingService, and the email becomes a listener on OrderPlaced.

Choosing: where does this logic go? ​

Fifteen rules from the ordering business, each sorted into a layer:

#Rule or codeGoes inKindReason
1An order line quantity is between 1 and 50OrderLine / OrderEntity / value objectNeeds only the line's own data
2Total = lines − promotions − loyalty + shippingPricingService.QuoteDomain serviceNeeds lines, tier and promotions together
3Only a draft order can be placedOrder.PlaceAggregateState transition of one aggregate
4Move 50.00 from wallet A to wallet B with a feeFundsTransferDomain serviceBelongs to neither account
5Load order, place it, save it, publish OrderPlacedPlaceOrderHandlerApplication serviceOrchestration of one use case
6A repeated Idempotency-Key returns the first resultPlaceOrderHandler (natural key) or decoratorApplicationProtocol concern, not a business rule
7Only logged-in customers with place-orders may call itForm Request authorize() / decoratorEdgeWho may run the use case
8items is a non-empty array of {sku, quantity}Form Request rules() / HTTP decoderEdgeShape, not meaning
9Authorize the card with Stripe, capture_method=manualStripePaymentGatewayInfrastructure serviceTechnology behind PaymentGateway
10What time is it?Clock adapterInfrastructure serviceThe domain receives now as an argument
11Map sales_orders rows to OrderEloquentOrderRepository / postgres.OrdersInfrastructure (repository adapter)Persistence detail
12Send the receipt email when an order is placedListener on OrderPlaced + Mailer adapterApplication (listener) + infrastructureReaction to an event; mail is technical
13Log every command with duration and correlation idLogsPlaceOrder / decorator.LoggingCross-cutting decoratorSame for every use case
14"My orders" page: last 20 orders with totalsCustomerOrdersHandler + read modelQuery handlerReads; changes nothing
15Capture payment when Fulfilment dispatches the parcelBilling's CapturePayment use case, on ParcelDispatchedApplication service in another contextBilling owns payment; Sales only reacts

Which kind of service? A short decision path:

QuestionYes →No →
Does it talk to a database, network, file, clock or random source?Infrastructure adapter behind a portNext question
Is it a business rule the domain expert would recognise?Next questionApplication service (orchestration) or edge (shape, auth)
Does it need only one entity's or value object's data?Method on that entity / value objectDomain service
Does it react to something that happened?Event listener calling a use caseUse case called by a driving adapter

In architecture: from a single process to a distributed system ​

The three kinds do not change as the system grows. What changes is what sits behind each port.

Monolith: one process, one database ​

Simplest correct version. A Laravel or Go monolith with folders Domain, Application, Infrastructure and one database. PlaceOrderHandler uses one DB::transaction. Catalog and Customers adapters may read the catalogue and customer tables directly, because one team owns all of it. Events can be in-process listeners with ShouldDispatchAfterCommit. Everyday example: a small shop where "place order" sends a receipt email and decrements stock in the same request.

The production version of the same monolith still benefits from the outbox for anything leaving the process (emails, webhooks to the warehouse), because an in-process listener dies with the process.

Modular monolith and multiple databases ​

Sales, Catalog, Identity, Fulfilment and Billing become modules with their own schemas (Modular Monolith). Now the Catalog port matters. Sales may not read catalog_products; it reads sales_price_list, a local copy fed by Catalog's PriceChanged events, or calls Catalog's published PHP or Go interface. The application service is unchanged; only the adapter moved. Each module has its own composition root (a service provider per module in Laravel; a NewApplication() per module in Go). Production example: an architecture test (Deptrac, Pest arch(), go-arch-lint) fails the build when Sales\Domain imports Catalog\Infrastructure.

Microservices: the port becomes a network call ​

When Sales becomes a service (where to draw that line is Service Boundaries), three ports change implementation, not shape:

  • PaymentGateway. In the sibling chapters Billing owns payments. At this scale Sales stops calling Stripe; the PaymentGateway adapter becomes a Billing client, or the payment step leaves PlaceOrder entirely. PlaceOrder then saves a pending_payment order and publishes OrderPlaced, and Billing authorizes and replies with PaymentAuthorized or PaymentFailed. That is a saga, and the void becomes a compensating step.
  • Catalog and Customers. HTTP or gRPC clients behind an anticorruption layer, with timeouts and circuit breakers (Service Communication), or local replicas fed by events.
  • Outbox. Unchanged, and now essential: the relay publishes to Kafka or RabbitMQ, and consumers in Fulfilment and Billing deduplicate with an inbox (Idempotent Consumers).
text
     Service       Use case / handler                  Talks through
1    Sales         PlaceOrder: save pending, outbox    -> broker: sales.order.placed.v1
2    Billing       AuthorizePayment (on OrderPlaced)   -> Stripe adapter; outbox: billing.payment_authorized
3    Sales         ConfirmOrder (on PaymentAuthorized) aggregate: pending -> placed
4    Fulfilment    ReserveStock (on OrderPlaced)       outbox: fulfilment.stock_reserved
5    Sales         CancelOrder (on PaymentFailed)      outbox: sales.order.cancelled.v1 (compensation)

Production example: the Go cmd/shop/main.go wiring is unchanged in structure. payments becomes a billingclient.Gateway, and catalog becomes a gRPC client with a 300 ms deadline.

Distributed data: replicas, caches and multi-region ​

  • Query handlers move first. CustomerOrdersHandler reads a replica or a projection. Users may not see their order for the replication lag, so return the new order's data from the command result, or route the reader's next query to the primary (Replication & Failover).
  • Caches sit behind query ports, never in front of command handlers. Invalidate them from events.
  • Idempotency becomes mandatory. Retries happen at every hop: client, gateway, queue, relay. The natural key (OrderID from Idempotency-Key) plus a unique constraint is the cheapest guarantee. Stripe keeps keys at least 24 hours, so your key must be stable for at least that long.
  • Clocks disagree across nodes. Use the Clock port for business time, but never to order events across services. Use sequence numbers or the broker's offsets for that.
  • Multi-region. Each region writes its own orders. Pricing rules (domain) are code and deploy everywhere. Price lists (data) replicate by events.

Scaling path: 1×, 10×, 100× ​

LoadWhat changesWhat does not change
1× (hundreds of orders/day)One process, in-process events, one databaseThe three kinds of service, the ports
10×Outbox + relay, queue workers for slow listeners, read replica for queriesUse case code; only adapters and wiring
100×Sales/Billing/Fulfilment as services, saga instead of inline payment, projections for queries, partitioned outboxDomain code: Order, PricingService

Lab: build, break and repair the layers ​

The Go part was run on the authoring machine. The Laravel part is expected, not run.

1. Run all Go tests (domain, application, adapter, dependency rule).

bash
cd docs/snippets/ddd/domain-application-infrastructure-services/go
gofmt -l . && go vet ./... && go test ./...
# ok  academy/domain-application-infrastructure-services/adapters/stripe
# ok  academy/domain-application-infrastructure-services/app/command
# ok  academy/domain-application-infrastructure-services/sales

2. Run the service with in-memory adapters and place an order (gold customer, 5 mugs + 2 teas).

bash
ADDR=127.0.0.1:18089 go run ./cmd/shop &
curl -si -X POST localhost:18089/orders -H 'Idempotency-Key: o-1001' \
  -d '{"customer_id":"c-gold","payment_token":"pm_card_visa","items":[{"sku":"MUG","quantity":5},{"sku":"TEA","quantity":2}]}'
# HTTP/1.1 201 Created
# {"order_id":"o-1001","total":"66.50 EUR"}

60.00 of mugs − 6.00 promotion + 16.00 of tea = 70.00; − 5% gold = 66.50; free shipping from 50.00.

3. Repeat the same request: idempotency.

bash
# same curl again
# HTTP/1.1 200 OK
# {"order_id":"o-1001","total":"66.50 EUR"}

4. Break a domain rule and watch which layer answers.

bash
curl -si -X POST localhost:18089/orders -H 'Idempotency-Key: o-1002' \
  -d '{"customer_id":"c-1","items":[{"sku":"MUG","quantity":99}]}'
# HTTP/1.1 422 Unprocessable Entity
# quantity must be between 1 and 50
# server log: {"msg":"command handled","command":"PlaceOrder","ok":false}   <- decorator, not the handler

5. Break the dependency rule. Add import _ "database/sql" to sales/pricing.go and run go test ./sales/. Expected: pricing.go imports database/sql: the domain must not depend on it. Revert.

6. Laravel (expected, not run). Copy the PHP snippets into a Laravel 13 app, register SalesServiceProvider in bootstrap/providers.php, run the migration, then:

bash
php artisan test --filter=PricingServiceTest      # 3 passed (no app booted)
php artisan test --filter=PlaceOrderHandlerTest   # 5 passed (fakes only)
php artisan test --filter=StripePaymentGatewayTest # 2 passed (Http::fake)

Then move the if ($tier === CustomerTier::Gold) block from PricingService into PlaceOrderHandler. PricingServiceTest fails on the gold case, which is exactly the signal that a rule has left the domain.

Common misconceptions ​

BeliefReality
"Every entity needs a domain service."Most rules belong on entities and value objects; a domain service is for operations that span several of them.
"The application service holds the business logic."It orchestrates. "It does not contain business rules or knowledge" (Fowler, summarising Evans).
"A domain service may call the repository whenever it needs data."Prefer that the use case loads data and passes it in; a domain service with I/O is no longer pure and is harder to test.
"Infrastructure is just the database."Clock, IDs, email, payment, storage, other services, feature flags: all infrastructure.
"Ports and adapters means an interface for every class."Ports sit at technology boundaries. A pure domain service needs no interface.
"Wrap the whole use case in a transaction, including the payment call."Network I/O inside a transaction holds locks and can charge for a rolled-back order. Call outside and compensate.
"Dispatching the event right after the state change is fine."Only after commit; otherwise consumers act on data that may roll back.
"Validation lives in one place."Shape at the edge, rules in the domain; duplicating a rule at the edge for UX is fine.
"Laravel facades are always wrong."They are fine in adapters, controllers and providers; the problem is facades inside domain classes.
"CQS means two databases."CQS separates handlers; CQRS with separate read models is optional.
"A queued job is a separate place for business logic."A job is a driving adapter: it builds the command and calls the same use case.
"Clean, hexagonal and onion are three different things to choose between."They share one rule (dependencies point inward); they differ in drawing and vocabulary.

Cheat sheet ​

TopicRemember
Domain serviceStateless, no I/O, named in the ubiquitous language, spans several domain objects
Application serviceOne use case: load, decide via domain, save, publish; no rules
Infrastructure serviceTechnical capability behind a port; adapters may use the framework
Dependency ruleSource code points inward; the domain imports nothing outward
PortInterface owned by the inside, phrased in its words
AdapterImplementation of a port with a technology; driving or driven
Composition rootmain.go or a service provider; the only place that knows concrete types
TransactionOwned by the application service; one aggregate per transaction
External callsOutside the transaction, with an idempotency key, compensated on failure
EventsRaised by the aggregate, stored with it (outbox) or dispatched after commit
Commands vs queriesCommand handlers change state through aggregates; query handlers read views
Cross-cuttingDecorators and middleware: logging, metrics, auth, idempotency, retries
ValidationShape at the edge (Form Request), rules in the domain
TestingDomain: pure table tests; application: fakes; adapters: contract/integration tests
NamingVerbs for use cases, concepts for domain services, technology for adapters

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why is "calculate the order total with promotions and loyalty tier" a domain service and not a method on Order? Must-know ​

Answer

Answer: Because it needs data the order does not own: the customer's tier (Identity) and the active promotions. Putting it on Order would force the order to know about promotions and tiers. It is still a domain rule, so it goes in a stateless domain service, PricingService, that receives all inputs as arguments.

2 — Read this line in an application service: if ($tier === 'gold') $total = intdiv($total * 95, 100);. What is wrong and where does it go? Must-know ​

Answer

Answer: A business rule (loyalty discount) is in the orchestration layer. It is untested by domain tests and will be duplicated by other entry points. It belongs in PricingService (or on a value object if it only needed one object's data).

3 — Why does PlaceOrderHandler call PaymentGateway.Authorize before opening the transaction rather than inside it? Important ​

Answer

Answer: A network call inside a transaction holds a connection and row locks for the provider's latency, and if the commit then fails you have an authorization with no order. Calling outside and voiding on failure keeps the transaction short and the side effect compensable.

4 — Two identical requests with the same Idempotency-Key arrive at the same moment. Both pass the "already exists?" check. What happens, and why must the loser not void the payment? Important ​

Answer

Answer: Both authorize with the same Stripe idempotency key, so they get the same PaymentIntent. The second insert fails with SQLSTATE 23505. Voiding would cancel the winner's authorization. The loser re-reads the order and returns it as a replay.

5 — Where is the port OrderRepository declared, and where is PaymentGateway declared? Why the difference? Must-know ​

Answer

Answer: OrderRepository is in the domain package, because it speaks only of aggregates. PaymentGateway, Clock and Outbox are in the application layer, because only use cases need them. In both cases the inside owns the interface and infrastructure implements it.

6 — Name two driving adapters and three driven adapters in the Laravel example. Important ​

Answer

Answer: Driving: PlaceOrderController with PlaceOrderRequest, and the PlaceOrderInBackground job (tests are a third). Driven: EloquentOrderRepository, StripePaymentGateway, SystemClock, DatabaseOutbox, DatabasePricingInputs.

7 — What is the difference between a command handler and a query handler in this chapter? Must-know ​

Answer

Answer: The command handler loads or creates an aggregate, runs in a transaction, raises events and returns a minimal result. The query handler reads a table, view or replica directly, loads no aggregate, raises no events and returns DTOs shaped for the caller.

8 — Why is ShouldDispatchAfterCommit not a full replacement for the outbox? Important ​

Answer

Answer: It waits for the commit, so it never announces a rollback. But the event lives only in process memory: if the process dies between commit and dispatch, the event is lost. The outbox row is committed with the order and survives crashes; the relay delivers it at least once.

9 — Is Cache::remember(...) inside an Eloquent model's business method a problem? What about inside an adapter? Important ​

Answer

Answer: Inside the model's business method, yes: it hides a dependency, ties the rule to a running cache and makes it untestable without the framework. Inside an adapter, no: adapters are where framework facades belong.

10 — How do you test each kind of service most cheaply? Must-know ​

Answer

Answer: Domain service: pure table-driven unit tests, no fakes. Application service: in-memory fakes for every port, asserting what was saved, published, charged and voided. Infrastructure adapter: contract or integration tests against httptest/Http::fake() or a real database in CI.

11 — When Sales becomes a microservice and Billing owns payments, what happens to the PaymentGateway port? Important ​

Answer

Answer: Either its adapter becomes a Billing client, or the payment step leaves PlaceOrder: Sales saves a pending order and publishes OrderPlaced, Billing authorizes and replies with an event, and Sales confirms or cancels. That is a saga; the void becomes a compensating step.

Glossary ​

TermMeaning
Domain serviceStateless domain operation that spans several entities/value objects; no I/O; named in the ubiquitous language
Application serviceObject that runs one use case by orchestrating repositories, domain objects and ports; holds no business rules
Use case / interactorClean Architecture's name for an application service
Command handlerApplication service for a state-changing command (CQS/CQRS vocabulary)
Query handlerApplication service that only reads and returns DTOs
Infrastructure serviceTechnical capability (payment, email, clock, storage) implemented as an adapter behind a port
Service LayerFowler/Stafford PoEAA pattern: the application boundary that controls transactions
Layered ArchitectureEvans's pattern: isolate the domain from UI, application and infrastructure code
Dependency ruleSource-code dependencies point only inward (Martin)
Dependency inversionHigh-level policy and low-level detail both depend on abstractions owned by the policy
PortInterface owned by the inside of the hexagon; driving (primary) or driven (secondary)
AdapterTechnology-specific implementation of a port, or a caller of one
Hexagonal architectureCockburn's ports and adapters: an inside with ports, outside adapters, no layers
Composition rootThe single place where concrete adapters are constructed and wired
Service containerLaravel's dependency-injection container; resolves constructor type hints
Service providerLaravel class that registers bindings; the module's composition root
Unit of workTracks changes of one business transaction and commits them atomically
TransactionDatabase-level atomic unit; owned by the application service
Domain eventSomething that happened in the domain, recorded by the aggregate
OutboxTable written in the same transaction as the aggregate; a relay publishes it after commit
ShouldDispatchAfterCommitLaravel interface: dispatch the event only after the open transaction commits
afterCommit()Laravel job-dispatch modifier: push the job only after open transactions commit
DTOData transfer object: plain input (command/query) or output data with no behaviour
Form RequestLaravel request class with authorize() and rules(): validation and authorization at the edge
DecoratorWrapper that implements the same interface and adds a cross-cutting concern
MiddlewareDecorator at the HTTP or bus level
ContextLaravel facade whose data is added to every log entry and shared with queued jobs
Idempotency keyClient-chosen key that makes a retried request return the first result
CompensationAn action that semantically undoes a side effect that cannot be rolled back (void an authorization)
CQSCommand-query separation: methods (or handlers) either change state or return data
CQRSSeparate models (and often stores) for writes and reads
Anemic domain modelEntities with data but no behaviour; rules live in services
Facade (Laravel)Static proxy to a container service, e.g. DB::, Cache::, Http::
Contract testTest that an adapter honours the wire contract of the external system
FakeWorking in-memory implementation of a port used in tests
Anticorruption layerAdapter that translates another context's model into ours
Wild WorkoutsThree Dots Labs' example Go project for DDD, CQRS and clean architecture

References ​

Built by Morteza Negahi