CodeBlanks Logo Icon CodeBlanks

Request/Response cycle

PHP course · Advanced · Lesson 68/92

Learn how middlewares chain between request and response.

The request/response cycle

In a middleware chain the request flows from the outside in, the response flows from the inside out. This is the onion model. The outermost middleware starts first, the innermost handler produces the response, then each middleware resumes where it left off.

Each middleware runs its before part before calling $next($request) and its after part after the call. If $next is never called, inner layers never run; this is handy for early returns.

Order matters: an outer middleware runs its before first and its after last, while an inner one is squeezed between the two ends.

Modifying the response

The $next($request) call returns a $response. You can return it as is, or modify it before returning. For example, you can append a header, filter the body, or produce a brand new response.

A common pattern: $response = $next($request); return $response . " [added]";. This automatically marks every response.

In cases like auth you can return a response without calling $next at all; that skips the inner layers.

Exercise Write a response-modifying middleware

Define a responseModifier($request, $next) function. First print echo "before", then take the response of $next($request), print echo "after". Append " [modified]" to the response and return it. The $handler returns "hello". Finally, print the response returned by responseModifier("istek", $handler).

Show example solution
Write function responseModifier($request, $next) { echo "before\n"; $response = $next($request); echo "after\n"; return $response . " [modified]"; }. Then call echo responseModifier("istek", $handler) . "\n";.
Example solution:
<?php
function responseModifier($request, $next) {
    echo "before\n";
    $response = $next($request);
    echo "after\n";
    return $response . " [modified]";
}
$handler = function ($request) {
    return "hello";
};
echo responseModifier("istek", $handler) . "\n";

Test yourself

  1. Match the cycle concepts

    request
    Flows inward
    response
    Flows outward
    $next
    Moves to the next layer
    onion model
    Layered processing
  2. What can a middleware do with the response from $next?

    • Modify it and return it
    • Ignore it and open a new request
    • Delete it
    • Only log it
    Show answer

    Modify it and return it — Correct. You can take the response from $next, modify it and return it.

  3. Return $response

        $response = $next($request);
        return ____;
    Show answer
        $response = $next($request);
        return $response;

All lessons in Advanced