PHP
The middleware pattern
Learn what the middleware pattern is and its place in request processing.
What is middleware?
In a web application, middleware are callables that run one after another while a request is processed. Each takes $request, does something (log, validate, modify) and passes control on with $next($request).
This pattern is called a pipeline or filter chain. Each middleware is a link; the request flows forward, the response flows back. One function doing everything is messier and less reusable.
In PHP a middleware is usually a Closure or a class method; $next represents the next middleware in the chain.
The before/after idea
If you place the $next($request) call in the middle, you can run code before and after it. The code before the call is the before phase; the code after is the after phase.
This is also called the onion model: the request moves inward through layers, the innermost handler produces a response, then the response moves outward through the same layers.
For example, echo 'before'; $r = $next($req); echo 'after'; prints 'before' first and 'after' later. You can also modify the response returned by $next.
Exercise Write a before/after middleware
Define a loggingMiddleware($request, $next) function. Before calling $next, print echo "before"; after the call, print echo "after". The $next($request) call returns "DONE". Finally, print the response returned by loggingMiddleware("istek", $handler).
Show example solution
Write function loggingMiddleware($request, $next) { echo "before\n"; $response = $next($request); echo "after\n"; return $response; }. Then call echo loggingMiddleware("istek", $handler) . "\n";.
Example solution:
<?php
function loggingMiddleware($request, $next) {
echo "before\n";
$response = $next($request);
echo "after\n";
return $response;
}
$handler = function ($request) {
return "DONE";
};
echo loggingMiddleware("istek", $handler) . "\n";
Test yourself
-
What is the core job of a middleware?
- Write directly to the database
- Process the request and pass it to the next step
- Produce an HTML page
- Load a PHP extension
Show answer
Process the request and pass it to the next step — Correct. A middleware processes the request and hands it off via $next.
-
The $next parameter
function loggingMiddleware($request, ____) {
return $next($request);
}
Show answer
function loggingMiddleware($request, $next) {
return $next($request);
}
-
Match the middleware pieces
- $next
- Next handler
- callable
- Invocable function
- before
- Part before $next
- after
- Part after $next
Next lesson: Request/Response cycle