Skip to content
Tutorials Center
My learning

Topics

Lesson 83 of 147 ยท PHP and the Web

Middleware and Request Pipelines

Learn how PHP middleware wraps a request handler in layers, the idea behind PSR-15, and build your own pipeline for auth, logging and CORS-style headers.

Almost every web request needs the same chores before your real code runs: check that the user is logged in, add security headers, log the request, measure how long it took. If you paste those into every controller you get duplication and bugs. Middleware solves this by wrapping your handler in layers. Each layer can inspect the request, stop it early, or change the response on the way back out.

Frameworks such as Laravel, Slim and Mezzio are built around this idea, and PHP has a standard for it, PSR-15. You do not need a framework to understand it: a middleware pipeline is a few closures and a loop. In this lesson you will build one from scratch, so the framework versions stop being magic.

The examples reuse the idea of a request and response from HTTP headers and redirects and the routing lesson. To keep them runnable, requests and responses are tiny immutable objects instead of the real superglobals.

The onion model

Picture an onion. The request travels inward through each layer to the handler at the center. The response travels back outward through the same layers in reverse order.

flowchart LR
    R["Request"] --> L["Logging"]
    L --> A["Auth"]
    A --> H["Handler"]
    H -.->|response| A
    A -.->|response| L
    L -.->|response| O["Client"]

Each middleware sees the request going in and the response coming out; any layer may answer early and skip the rest.

That symmetry is the point. A timing middleware starts the clock before calling the next layer and reads it after. An auth middleware can return 401 immediately and the handler never runs.

The PSR-15 shape

PSR-15 defines two interfaces. A request handler turns a request into a response. A middleware receives the request and the next handler:

PHP
interface RequestHandlerInterface
{
    public function handle(ServerRequestInterface $request): ResponseInterface;
}

interface MiddlewareInterface
{
    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface;
}

Calling $handler->handle($request) means "continue inward". Not calling it means "stop here". We will use the same shape with our own small classes so the code runs without installing PSR packages.

Building the pipeline

First the pieces: an immutable Request and Response, and the two interfaces. Immutability matters, because middleware changes things by creating modified copies with with... methods, as the readonly lesson describes.

PHP A middleware pipeline from scratch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Study the output. Logging prints on the way in and on the way out. In the denied case, Auth returns before the core runs, but the response still travels back out through SecurityHeaders and Logging, so even the 401 gets its header and its log line.

The Pipeline class wraps the stack from the inside out. For the stack [Logging, SecurityHeaders, Auth] it first wraps the core with Auth, then wraps that with SecurityHeaders, and finally with Logging. The result is a single Handler that behaves like one object, so pipelines can even nest inside other pipelines.

A compact version with closures

You will often see the same idea written with array_reduce and closures, the style used by many micro-frameworks:

PHP The pipeline as nested closures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

wrap runs first on the way in, trim last. On the way out the order reverses: the core returns handled: hello, shout uppercases it, and wrap adds the brackets. Closures are shorter, classes are easier to test and configure; both are the same pattern. See anonymous functions and functional array functions for the building blocks.

Order matters

Put middleware in an order that makes sense:

  • Error handling goes outermost, so it can catch exceptions from everything inside.
  • Logging and timing next, so they see every request, including rejected ones.
  • Security headers and CORS before auth so that even error responses carry them.
  • Authentication, then authorization, since you need to know who the user is before checking what they may do.
  • Body parsing and validation just before the handler.

Per-route middleware is the same idea applied to a smaller pipeline: a /admin route group gets an extra Auth layer that public routes do not.

Common mistakes

  • Forgetting to return the response. A middleware that calls $next->handle() but doesn't return the result breaks everything outward.
  • Mutating shared state. Prefer immutable requests, as shown with withAttribute, so one layer cannot surprise another.
  • Heavy work in every request. Middleware runs for every matching request. Keep it fast; cache lookups.
  • Hiding business logic in middleware. It is for cross-cutting concerns. Rules about orders or invoices belong in your domain code.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a middleware do when it does not call the next handler?

    Not calling the next handler short-circuits the pipeline. An auth middleware uses this to return 401 without running the inner layers or the core handler.
  2. 2. With the stack Logging, SecurityHeaders, Auth, in which order do they see the response on the way out?

    The response retraces the path of the request in reverse, like the layers of an onion.
  3. 3. Why are requests and responses usually immutable in PSR-15 style code?

    Returning modified copies keeps each layer's view of the request predictable and avoids hidden side effects.
  4. 4. Where should error-handling middleware usually be placed?

    Outer layers wrap inner ones, so a try/catch in the outermost middleware can turn any exception below it into a proper error response.

Summary

  • Middleware wraps a request handler in layers; each layer can act before and after the inner ones, or stop the chain.
  • PSR-15 standardizes process($request, $handler); the same pattern works with plain classes or closures.
  • A pipeline wraps handlers from the inside out so the first piped middleware runs first.
  • Responses travel back through the layers in reverse order.
  • Order matters: errors outermost, then logging, headers, auth, and parsing.
  • Use middleware for cross-cutting concerns, not business rules.

Next: PHP and Databases