Types of middlewares that you can add which will be called before the route handler will be executed. This middleware can transform common parameters $route and $parameters into something different.
- Multiple global middlewares that will be called in order of attachment
- Multiple route specific middlewares that will be called in order of attachment
Order of execution of the middlewares
- Global middlewares
$router->addRoute('*', ...)
- Before calling route callback
$router->addRoute('/example', ...)
all those matching the route will be executed
Let's look at a simple example:
$router = new Router();
$router->addRoute('/user/[i:id]', function(string $route, array $parameters){
$userModel = new UserModel();
$userObject = $userModel->getUserById($parameters['id']);
// use $userObject for any purpose you need
});
Now let's watch an example with all the possibilities
$router = new Router();
// First step. We have an API that talks JSON, convert the body
$router->registerMiddleware('*', function (string $route, array $parameters){
$request = Request::createFromGlobals();
$parameters['_request'] = $request;
$parameters['_body'] = json_decode($request->getContent(), true);
return $parameters;
});
// Second step. Ensure that we are logged in when we are in the private area
$router->registerMiddleware('*', function (string $route, array $parameters){
// Is not a private area
if (mb_strpos($route, '/user') !== 0 || empty($parameters['user_id'])) {
return $parameters;
}
$token = $parameters['_request']->headers->get('oauth_token');
$auth = new SomeAuth();
$auth->validateTokenOrFail(
$token,
$parameters['user_id']
);
// We don't need to return nothing
});
// Last step. Now we will modify the parameters so the handler can work with them
$router->registerMiddleware('/user/[i:user_id]', function(string $route, array $parameters){
$userModel = new UserModel();
return $userModel->getUserById(
$parameters['user_id']
);
});
// Final destination. We have ended the middlewares, now we can work with the processed data
$router->addRoute('/user/[i:user_id]', function (UserObject $userObject){
// Do everything
});
Learn more
More information can be found here:
Top comments (0)