N-tier architecture in PHP means splitting an application into distinct horizontal layers—typically presentation, application/service, domain, and data access—that talk downward through defined interfaces and never skip levels. The method is straightforward: define the layers and their contracts first, then build outward from the data layer while keeping framework code out of the core. PHP’s shared-nothing request model makes this more achievable than in long-running runtimes, but only if you enforce boundaries with dependency injection, autoloading conventions, and honest layer rules that entry-point code respects.

This guide walks through the design decisions that actually matter, in the order you would make them. It covers what each tier owns, how to wire it, where N-tier diverges from clean or hexagonal architecture, and the failure patterns that turn nominal layers into decorative folders.

What N-Tier Architecture Looks Like in a PHP Codebase

The "N" in N-tier is honest about one thing: you choose the number. A classic PHP web application fits naturally into four tiers.

Presentation tier. Controllers, request/response handling, view templates, JSON serializers, and anything that exists because a browser, mobile client, or API consumer exists. This tier translates HTTP into application calls and back.

Application/service tier. Use cases. "Register a user," "place an order," "recalculate invoice totals"—each is one orchestration unit. This tier owns transactions, coordinates repositories, enforces authorization context, and returns results. It contains application logic, not business rules.

Domain tier. Entities, value objects, aggregates, and domain services. The business invariants live here: an order cannot exceed its credit limit, an email must normalize before storage, a discount never stacks below zero.

Data/infrastructure tier. Repositories backed by PDO or an ORM, message queue adapters, cache implementations, mailers, and external HTTP clients. This tier implements interfaces declared by the layers above it.

The critical discipline is directional dependency. Presentation depends on application; application depends on domain; infrastructure implements contracts defined closer to the domain. Nothing in the domain ever imports a database class. That single rule, consistently applied, buys most of the architectural value.

A fifth tier sometimes appears as a separate API or integration boundary, but in PHP it usually collapses into presentation for inbound traffic and infrastructure for outbound calls. Physical separation onto different servers is a deployment concern layered on top of the same logical design; it changes configuration, not folder structure.

Prerequisites and Project Skeleton Before the First Controller

You need PHP 8.1 or newer (enums, readonly properties, and first-class callable syntax all make boundary code cleaner), Composer for autoloading, and a database you can reach from a test harness. A front-controller pattern—everything routed through public/index.php—keeps web entry points in one place. Nothing here requires a framework, but if you use one, its container can serve as the wiring mechanism as long as your domain stays framework-free.

A workable starting skeleton:

Composer autoload maps App\ to src/. Layer namespaces mirror folders, so an illegal import is visible at a glance in review. Keep the repository interfaces in Domain/Repository even though their implementations live in infrastructure—that placement makes the inversion explicit.

Before writing code, decide one thing: how dependencies will be supplied. A small container (even a hand-written one registering service definitions in config/services.php) is enough. Constructor injection throughout is the rule; service locators and static facades inside application or domain code are the first boundary leak you will regret.

Step-by-Step: Building Each Tier in Working Order

Build from the inside out. Data and domain first means the application tier is written against real, tested collaborators rather than mocks of things that do not exist yet.

1: Define domain value objects and entities. Start with the invariants you can test without a database: Email normalizes and validates on construction, Money refuses mixed currencies, OrderLine rejects negative quantities. Give entities behavior—$order->addLine() rather than public setters—so rules have a home. Success check: each test constructs the object directly with no database and no container.

2: Declare repository interfaces in the domain layer. Method signatures use domain types, never arrays or query builders: findById(OrderId $id): ?Order, save(Order $order): void. Resist returning pagination objects tied to SQL. Expect this step to feel premature; it is the contract the next two steps consume.

3: Implement repositories in infrastructure. Write the PDO or ORM version against the interface. The implementation owns mapping rows to entities, transaction handling for that specific persistence operation, and nothing else. Failure signal: if the repository starts computing discounts or sending emails, behavior has drifted out of the domain.

4: Write application services as use-case orchestrators. One public method per use case is a reliable default. The service loads aggregates through interfaces, calls domain methods, persists, and returns a DTO. It opens and commits transactions when a use case spans multiple writes. Keep the method short enough to read in one screen; if it needs a diagram, split the use case.

5: Build presentation controllers thin. A controller parses and validates the request (structure and types, not business rules), calls exactly one application service, and formats the response. Validation of business rules belongs in the domain; request-shape validation can sit here or in a small request object. Three to ten lines per action is typical.

6: Wire everything in the composition root. public/index.php and your container configuration are the only places that name concrete infrastructure classes. Route registration, service definitions, and environment configuration live together. This is the seam where testing, production, and staging diverge.

7: Exercise an end-to-end path. Write one test that boots the container with a SQLite in-memory or test database, dispatches a request through the controller, and asserts on the response and the persisted row. That single test catches most wiring errors.

The expected result after step 7 is a slice of working functionality—say, user registration or order creation—with every layer present and no shortcuts across tiers. Check success by inspecting imports: no file under Domain/ should reference Infrastructure/, PDO, or a framework namespace.

Wiring Layers Without a Framework (and With One)

A hand-rolled container is roughly thirty lines: a definition map from interface to factory closure, resolved lazily and cached. That is sufficient for most applications and keeps the wiring transparent.

In Symfony or Laravel, the service container replaces this file, and the architectural rules do not change: controllers resolve services by type, never instantiate repositories, and framework facades stay out of application and domain code. If a framework facility is genuinely useful in the domain layer—a clock abstraction, say—wrap it behind your own interface and let infrastructure adapt it.

One PHP-specific trap: autoloading can make illegal dependencies invisible until runtime. Enable static analysis (PHPStan or Psalm at a strict level) and add a rule or custom check that forbids App\Infrastructure imports from App\Domain and App\Application. A five-line architecture test using a namespace scanner catches violations in CI before they spread.

Where N-Tier Ends and Clean or Hexagonal Architecture Begins

N-tier and clean architecture overlap substantially; the difference is emphasis. N-tier describes horizontal layers with allowed downward dependencies and is typically organized by technical concern. Clean and hexagonal architecture emphasize the dependency rule—inner layers define ports, outer layers adapt—and are organized by domain concept.

In practice, a PHP implementation that puts repository interfaces in the domain and keeps the domain free of framework code is already doing the dependency inversion that clean architecture prescribes. The labels matter less than the enforcement. If someone on the team says "we do N-tier," they usually mean layered services with a data access tier; if they say "hexagonal," they usually mean ports and adapters with explicit inbound and outbound boundaries. Both produce maintainable systems when transaction boundaries and domain invariants get real attention.

What genuinely differs is vertical slicing. Classic N-tier funnels every request through the same horizontal path, which can produce shallow service classes that mostly forward calls. Organizing use cases by feature—src/Order/, src/Billing/, each with its own internal layering—reduces cross-feature coupling. You can adopt N-tier rules per module with a shared infrastructure kernel and get most of both worlds.

Testing Strategy That Follows the Tier Boundaries

Each tier carries a different test cost, and the architecture is what makes cheap tests possible.

Domain unit tests need no database, container, or HTTP. They construct entities, call behavior, and assert on invariants—the fastest and highest-value layer. Aim for these to dominate the suite.

Application service tests use in-memory or fake repository implementations that satisfy the domain interfaces. They verify orchestration: does placing an order save exactly once, does a failed payment leave the transaction rolled back. Because the interfaces already exist, no mocking framework is required; hand-written fakes are usually clearer.

Repository integration tests run against a real database—a Dockerized Postgres, or SQLite when SQL compatibility allows. Verify row mapping, pagination queries, and cascade behavior. These are slower and fewer.

End-to-end tests exercise the front controller and catch container wiring and routing errors that unit tests cannot see.

The failure mode to watch for is the inverted pyramid: many HTTP-level tests, few domain tests, long runtimes, and brittle assertions on rendered markup. Layer boundaries do not fix that by themselves, but they make the cheaper test levels possible, and the architecture earns its keep only when the suite reflects it.

Transactions, Boundaries, and the Failures N-Tier Invites

Transactions belong in the application tier. A use case that writes across two repositories should wrap both writes in one transaction, opened and committed by the service, not buried in each repository method. Repositories that quietly manage their own transactions create partial-commit bugs when composed.

Three failure patterns recur in PHP N-tier builds:

Anemic domain, transactional services. Entities become property bags and all logic migrates into services, which then grow into thousand-line god objects. The symptom is a service that knows every business rule while Order knows none. The fix is to push invariants back into entities early, before the service layer feels like the natural home.

Repository leakage. Query builders or ORM entities cross into the domain, dragging SQL semantics into business code. Once where() calls appear outside infrastructure, the Portability of the domain layer is gone. Keep the interfaces narrow and value-based.

Layer theater. Folders exist, but controllers reach into repositories directly for "simple" cases, and the application tier is bypassed whenever it is convenient. This is the most common and most corrosive problem, because each exception looks reasonable in isolation. Enforce the rules in CI with architecture tests rather than relying on review vigilance.

A fourth, subtler issue is the shared database tier across multiple services. N-tier is a code architecture; distributing tiers across servers with a shared database reintroduces coupling at the schema level. If you separate services, separate their data ownership too, or you have copied the monolith's tightest binding.

A Small Worked Slice: Cost of Adding One Use Case

Consider an application that already supports placing orders and now needs a refund feature. With layers in place, touching each tier is mechanical:

Domain: add Order::refund() enforcing that refunds never exceed captured payments, plus a Refund value object. Interface: extend OrderRepository with findByIdForUpdate() if row locking is needed. Infrastructure: implement the new query using SELECT ... FOR UPDATE. Application: a RefundOrderService that loads the order, calls refund(), persists, and records the event. Presentation: one controller action and one route. Wiring: one service definition.

The measurable difference from an unlayered codebase is not speed—it is the blast radius of the change. You add a test at each level and nothing else in the system needs to know the feature exists until the route is registered. That predictability is the actual return on the architectural investment, and it accumulates with each use case. If features instead require edits scattered across unrelated files, the layers are not real, regardless of what the folders say.

The cost side is honest too: more files, more indirection, and more ceremony for simple CRUD. For small applications or timeboxed prototypes, a well-structured two-layer approach (controllers plus a service layer with direct SQL) often beats enforced N-tier. Adopt N-tier when business rules are substantial, when multiple clients share application logic, or when the team is large enough that boundaries need to be explicit rather than assumed.

FAQ

Does N-tier require separate servers? No. The layers are logical boundaries in code. Deploying the presentation tier on web servers and the data tier on a database host is a deployment topology, and it can be applied to a logically layered monolith without changing a single class.

Can I use an ORM and still keep the domain clean? Yes, if ORM entities or query objects stay inside infrastructure. The pattern is repository implementations that map between ORM records and domain entities, with interfaces declaring only domain types. Some teams accept ORM annotations on domain entities as a pragmatic compromise; if so, invoke it consistently and keep the ORM out of everything else.

How many tiers are enough for a typical PHP app? Four is the common default: presentation, application, domain, infrastructure. Fewer usually merge the domain into services; more typically adds a separate API boundary or shared kernel. Pick the smallest count that keeps invariants testable without infrastructure.

What belongs in a controller versus a service? The controller translates transport: parsing request data, shaping responses, HTTP status codes. The service owns the use case: which aggregates to load, what transaction to wrap, which domain operations to invoke. Business rules belong in neither—they belong in the domain.