Sobes.tech
Middle

What is middleware?

sobes.tech AI

Answer from AI

Middleware is a layer of software or a framework that processes incoming HTTP requests before they reach the final handler (e.g., controller), and outgoing HTTP responses after processing. It performs various actions such as authentication, authorization, logging, modification of request/response, etc. Middlewares typically form a pipeline where each middleware performs its function and passes the request to the next or final handler.

Example in PHP (using PSR-7/PSR-15):

<?php

use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class AuthenticationMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // User authentication check
        if (!$this->isAuthenticated($request)) {
            // If user is not authenticated, return an error
            return new \Slim\Psr7\Response(401); // Example of creating a PSR-7 response
        }

        // If authenticated, pass the request to the next handler
        return $handler->handle($request);
    }

    private function isAuthenticated(ServerRequestInterface $request): bool
    {
        // Authentication logic (e.g., header, session, etc.)
        return true; // Stub
    }
}

class LoggingMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // Log request info before processing
        $method = $request->getMethod();
        $uri = (string) $request->getUri();
        error_log("Handling request: $method $uri");

        // Pass request to next handler and get response
        $response = $handler->handle($request);

        // Log response info after processing
        $statusCode = $response->getStatusCode();
        error_log("Response status: $statusCode");

        // Return response
        return $response;
    }
}

// Usage example in router (simplified)
// $router->addMiddleware(new AuthenticationMiddleware());
// $router->addMiddleware(new LoggingMiddleware());
// $router->addRoute('GET', '/profile', new ProfileHandler());

Middlewares allow decomposing request processing logic, making the code more modular, reusable, and testable. They follow the "single responsibility" principle.

What is middleware? — PHP - sobes.tech