Middlewares

Middlewares provide a clean and structured way to execute logic before a route action is performed. In most applications, certain checks must run prior to executing controller logic — such as verifying authentication, validating permissions, or preparing request data. Middlewares allow you to centralize these responsibilities and keep controllers focused only on business logic.

SigmaPHP uses class-based middlewares. When attaching a middleware to a route, the router expects both the middleware class name and the method that should be executed.

Creating a Middleware

Creating a middleware is straightforward using the CLI assistant. The following command generates a new middleware class automatically.


 ./bin/sigma-cli create:middleware Auth
        

This command creates the Middlewares directory inside app/ (if it does not already exist) and generates the AuthMiddleware.php file.


<?php

namespace App\Middlewares;

use SigmaPHP\Core\Router\BaseMiddleware;

class AuthMiddleware extends BaseMiddleware
{
    /**
     * Handle the incoming request.
     *
     * @return mixed
     */
    public function handle()
    {
        //
    }
}
        

Using a Middleware

Middlewares are attached directly to routes through the middlewares option.


$routes = [
    [
        'name' => 'orders.create',
        'path' => '/orders',
        'method' => 'post',
        'middlewares' => [
            AuthMiddleware::class,
            UserCanCreateOrderMiddleware::class,
        ],
        'controller' => OrderController::class,
        'action' => 'create'
    ],
];
        

When a request matches the route, the middleware runs first. If the middleware allows execution to continue, the controller action will be executed normally. Otherwise, the middleware may return a response such as a redirect or an error.

BaseMiddleware Methods

All middlewares extend BaseMiddleware, which provides a set of built-in methods that can be used directly inside your middleware class. For example, you may verify if a user session exists before allowing access to a protected route.

The middleware can perform common tasks such as redirecting the user to a specific URL or route, returning the user to the previous page, accessing and managing sessions, cookies, uploaded files, and retrieving the current request instance. These methods allow you to implement authentication, authorization, and validation logic without manually interacting with low-level HTTP handling.


public function handle()
{
    if (!$this->session()->has('user')) {
        return $this->redirect('/login');
    }
}
    

By centralizing this behavior inside middlewares, access control remains clean, reusable, and consistent across your application while keeping controllers focused only on business logic.

Available BaseMiddleware Methods

The following methods are available through $this-> inside any middleware extending BaseMiddleware:

Back to top