PSR-15 standardizes server-side middleware around PSR-7 requests and responses.
What It Does
PSR-15 standardizes server-side middleware around PSR-7 requests and responses. The following examples distinguish a normal use case, a boundary case and a practical application.
Requirements and Compatibility
PHP 8.x and a local test environment. Apply input validation, correct error handling and the requirements of any optional libraries.
The code focuses on the core concept. Production implementation may also need routes, validation, persistence, authorization or deployment tooling.
Example 1: Basic Behavior
Understand the primary operation and its inputs.
<?php
$middleware = fn (array $request, callable $next): array => $next($request + ['trace' => 'abc']);
$result = $middleware(['method' => 'GET'], fn ($r) => $r);
print_r($result);
Example 2: Another Case
Check failure behavior or a different execution path.
<?php
$middlewares = [fn ($r, $next) => $next($r + ['a' => 1]), fn ($r, $next) => $next($r + ['b' => 2])];
$handler = fn ($r) => $r;
foreach (array_reverse($middlewares) as $mw) { $next = $handler; $handler = fn ($r) => $mw($r, $next); }
print_r($handler([]));
Practical Example: Putting It to Use
Apply the behavior in a small, controlled scenario.
<?php
interface MiddlewareContract { public function process(array $request, callable $next): array; }
class AddHeader implements MiddlewareContract { public function process(array $request, callable $next): array { $response = $next($request); $response['X-Demo'] = 'on'; return $response; } }
print_r((new AddHeader())->process([], fn ($r) => ['status' => 200]));
// PSR-15 implementations use PSR-7 objects, not arrays.
Important Behavior and Edge Cases
A simple array callback pipeline is educational but not a standards-compliant PSR-15 implementation.
Comparison with Related Functions or Approaches
| Option | What it means in practice |
|---|---|
| PSR-15 Middleware Explained | PSR-15 standardizes server-side middleware around PSR-7 requests and responses. |
| Related approach | Use RequestHandlerInterface and MiddlewareInterface from PSR packages in real applications. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the important boundary for PSR-15 Middleware Explained | A simple array callback pipeline is educational but not a standards-compliant PSR-15 implementation. |
| Assuming a related mechanism has the same behavior | Use RequestHandlerInterface and MiddlewareInterface from PSR packages in real applications. |
Key Takeaways
- PSR-15 standardizes server-side middleware around PSR-7 requests and responses.
- A simple array callback pipeline is educational but not a standards-compliant PSR-15 implementation.
- Use RequestHandlerInterface and MiddlewareInterface from PSR packages in real applications.
Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.