📡 You're offline — showing cached content
New version available!
Quick Access
PHP Beginner

PHP Middleware Pattern: HTTP Request Pipeline

Learn middleware — HTTP pipelines, PSR-15, and building custom middleware.

EzyCoders Admin April 16, 2026 2 min read 1 views
PHP Middleware Pattern: HTTP Request Pipeline
Share: Twitter LinkedIn WhatsApp

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.

EzyCoders Admin
Written by
EzyCoders Admin

Team Lead and Full-Stack Developer with experience in PHP, JavaScript, SQL, DSA, and System Design. Passionate about software engineering, scalable web technologies, and helping developers prepare for coding interviews and tech careers through practical tutorials and professional guidance.

Comments (0)

No comments yet. Be the first!

Leave a Comment