Skip to content

Lesson 9 of 9 · 23m

Modern PHP Architecture: Boundaries, Exceptions, and Dependency Injection

How to structure PHP 8.x applications so types, tests, and operations reinforce each other instead of merely surrounding legacy chaos.

The final difference between legacy PHP and modern PHP is not syntax. It is whether the application has boundaries you can reason about. In a healthy system, HTTP input becomes validated data, application services enforce use cases, domain objects protect invariants, and infrastructure implements narrow interfaces. In a legacy system, everything can touch everything, so every refactor is a trust exercise.

Push frameworks to the edge

Controllers should translate, not decide:

final class InvoiceController
{
    public function issue(Request $request, IssueInvoice $useCase): Response
    {
        $input = IssueInvoiceInput::fromRequest($request);
        $invoiceId = $useCase->execute($input);

        return new JsonResponse(['id' => $invoiceId->toString()], 201);
    }
}

The framework is excellent at routing, middleware, sessions, and serialization. It is not a domain model. When business rules are embedded in controllers, every new transport — CLI, queue worker, webhook — duplicates or bypasses them.

Constructor injection is a design document

final class IssueInvoice
{
    public function __construct(
        private readonly InvoiceRepository $invoices,
        private readonly TaxCalculator $tax,
        private readonly EventBus $events,
        private readonly Clock $clock,
    ) {}
}

The constructor tells you the use case's collaborators and therefore its complexity. If it needs the container, request object, cache, mailer, logger, payment gateway, and twelve repositories, dependency injection did not create good design; it merely mechanized service location. Split by use case, not by vague nouns.

Exceptions are for broken invariants, not flowchart arrows

Domain failures that users can correct — invalid coupon, insufficient stock — often deserve typed result objects or explicit validation errors. Infrastructure failures and violated invariants deserve exceptions:

if (!$invoice->status()->canTransitionTo(InvoiceStatus::Issued)) {
    throw new DomainException("Invoice {$invoice->id()} cannot be issued from {$invoice->status()->value}");
}

At the boundary, map exceptions deliberately: domain validation to 422, authentication to 401/403, unexpected failure to 500 with correlation IDs. Never serialize exception messages wholesale into API responses. “SQLSTATE duplicate entry” is an internal detail and sometimes an information leak.

Composition over global convenience

Facades and helpers are useful inside framework edges, but static access inside the domain destroys substitutability. You cannot replace a global cache in a test if the code reaches for it directly. Pass narrow interfaces inward. Keep logging and observability universal, but keep behavior-bearing dependencies explicit.

Test the shape, not just functions

Architecture should produce three test levels: fast unit tests for domain rules, application tests for use cases with in-memory infrastructure, and a smaller set of HTTP or CLI tests proving the wiring. If every test boots the framework, you do not have a test suite; you have a very slow deployment rehearsal.

Field notes

  • A repository interface belongs to the application's needs, not to the ORM's table layout. Do not leak query builder objects through it.
  • Constructor injection plus readonly properties removes an entire category of test-reset bugs.
  • Clock abstractions matter because time is input. Date-dependent bugs are brutal when now() is hidden everywhere.
  • Correlation IDs should enter at middleware and leave through logs, queues, and outbound HTTP headers.
  • Modern architecture is incremental. Introduce use cases around new work, then let adjacent legacy code shrink until replacement is no longer dramatic.

Was this lesson helpful?

Sign in to rate