Create Custom Middleware

Write your own middleware for this framework

To write custom middleware for this framework, one has to make sure the API constraint is satisfied. The recommended way to create middleware is to extend the sirJuni\Framework\Middleware\Middleware class, which is an abstract class with 2 methods.

  1. set_fallback_route($route) : This method is used to configure a fallback route, to which a redirect is caused when the constraints in middleware fail. To save $route we have to make a static variable to store it.

  2. handle($request) : This method is used by the Router to give the Middleware control of the request. So, this serves as an entry point into the middleware and it would be useless to create a middleware without this method.

A code example of creating a middleware would be

use sirJuni\Framework\Middleware\Middleware;

class CheckStat extends Middleware {
    static $route;
    
    public static function set_fallback_route($route) {
        self::$route = $route;
    }
    
    // only serve the page if '/' is visited
    public static function handle($request) {
        if ($request->url() == '/') {
            return TRUE;   // return true on success
        }
        else {
            HelperFuncs::redirect(self::$route);  // cause redirect on failure
        }
    }
}

The handle($request) function should return TRUE if conditions meet, otherwise just cause a redirect to fallback_route.

Last updated