Middlewares

Middlewares are layers functioning in between of the request and the application. Each middleware can perform several actions and then forward the request to next middleware up to the controller, or terminate the flow by redirecting to diffrent route.

In the bellow code there are there middlwares applied to routes, auth and web are applied to entire route group post, where the middleware editor are applied to one route inside the group.

return function($route){
    $route->group('post', function() use($route){
        $route->add('post', 'GET', 'MainController', 'getPosts');
        $route->add('post/[:num]', 'GET', 'MainController', 'getPost');
        $route->add('post/amend/[:alpha]/[:num]/?', 'POST|PUT', 'MainController', 'amendPost')->middlewares(['editor']);
    })->middlewares(['auth', 'web']);
};

        

First the group middlewares will be executed and then middleawares inside the group so the middleware editor will be executed after auth and web.


Defining middlewares

Middlewares are classes which are exctening the base Qt_Middleware and are located under directory Middleware of the current module.

namespace Modules\Main\Middlewares;

use \Quantum\Middleware\Qt_Middleware;
use Quantum\Http\Request;

class Auth extends Qt_Middleware {

    public function apply(Request $request, \Closure $next) {
        if(!session()->has('loggedin')) {
            $request->set('auth', 'ok');
            
            return $next($request);
        }
        
        redirect('/');
    }

}
        

The method apply executes the middleware code, you can modify the request content and pass it to the next middleware in queue or to your Controller action or redirect someware else if it's not passing the condition.

<< Prev Next >>