Architecture

Build a Middleware Pipeline for Custom PHP Applications

Separate cross-cutting request concerns such as authentication, request IDs and rate limiting from individual route handlers.

Overview

Middleware is code that runs around a request handler. It is useful for concerns shared by many routes: request IDs, authentication, access logging, rate limiting and response headers. A small custom PHP application can use middleware without adopting a full framework.

Define a clear contract

A middleware receives a request and the next handler, then returns a response. Keep the contract small and consistent. Avoid mixing raw superglobals, database access and HTML rendering in every middleware.

interface Middleware
{
    public function process(
        ServerRequest $request,
        RequestHandler $next
    ): Response;
}

The request, handler and response types may be your own lightweight abstractions or PSR-7-compatible implementations.

Order matters

A typical pipeline might assign a request ID, apply security headers, enforce request-size limits, authenticate the user, authorize the route and finally invoke the controller. Some middleware should run even when later steps fail, so response handling and exception boundaries must be deliberate.

Keep route-specific policy explicit

Authentication middleware can establish the current identity, but authorization should still check whether that identity may perform the requested action on the requested resource. Do not assume that being logged in means every route is permitted.

Avoid hidden side effects

Middleware should have one clear responsibility and should not silently modify unrelated application state. Make ordering visible in bootstrap code and test the pipeline with both successful and rejected requests.

Checklist

  • Define request, response and handler contracts.
  • Register middleware in a visible order.
  • Keep each middleware focused.
  • Separate authentication from authorization.
  • Ensure exceptions still produce consistent responses.
  • Test early exits and downstream handler behavior.

References

PHP-FIG PSR-15 · PHP-FIG PSR-7

Share this page Help other developers discover this resource.