What is it?
Middleware sits between HTTP request and application logic — handling auth, logging, rate limiting, CORS.
Why does it matter?
Middleware is the architecture behind every PHP framework's request handling.
Learn middleware — HTTP pipelines, PSR-15, and building custom middleware.
Real-World Use Cases
- 💡 Use case - Practical.
- ⚡ Performance - Critical.
- 🏢 Professional - Industry.
- 📚 Learning - Essential.
Core
Middleware = layered processing between request → response.
Each layer can read, modify, or block the request.
Example
class Pipeline {
private $middlewares = [];
public function add($mw) {
$this->middlewares[] = $mw;
}
public function handle($request) {
$handler = fn($req) => "Final Response";
foreach (array_reverse($this->middlewares) as $mw) {
$next = $handler;
$handler = fn($req) => $mw($req, $next);
}
return $handler($request);
}
}
// Middleware
$auth = fn($req, $next) =>
isset($req['user']) ? $next($req) : "Unauthorized";
$log = fn($req, $next) => (print "Log\n") ? $next($req) : null;
// Usage
$p = new Pipeline();
$p->add($log);
$p->add($auth);
echo $p->handle(['user' => 'admin']);
Real Use Cases
- Authentication / Authorization
- Logging & Monitoring
- Input validation
- Rate limiting
- CORS / headers
Best Practice
- Keep middleware small & single-purpose
- Maintain correct order (auth first)
- Use PSR-15 for interoperability
- Avoid heavy DB logic inside middleware
- Pass data via request attributes
Q: What is PSR-15?
PSR-15 defines interfaces for HTTP server middleware. Middleware written to PSR-15 works in Laravel, Slim, and any compatible framework.
Comments (0)
No comments yet. Be the first!
Leave a Comment