How to Create Middleware

Creating Middleware Filters

Middlewares act as HTTP request-filters. They reside under src/Middleware/ or src/Http/Middleware/ (such as AuthMiddleware to guard dashboards, and CsrfMiddleware to protect POST form submissions) and operate using a decoupled onion-style handler pipeline.

Core Auth Middleware Implementation

Core Auth Middleware Implementation php
namespace Zero\Http\Middleware;

class AuthMiddleware
{
    protected static $loginUrl = '/admin/login';

    public function handle(callable $next)
    {
        App::ensureSession();

        // Invalidate session if user does not exist inside our database!
        if (!isset($_SESSION['user_id']) || App::getCurrentUser() === null) {
            $_SESSION['redirect_to'] = $_SERVER['REQUEST_URI'] ?? '/admin/dashboard';
            
            if (isset($_SESSION['user_id'])) {
                App::logoutUser();
            }
            
            header('Location: ' . self::$loginUrl);
            exit();
        }

        // User is logged in and valid, proceed down the next pipeline callback!
        return $next();
    }
}