在苗条的条件下重新定向整个组

时间:2015-09-30 08:04:13

标签: authentication redirect routes slim

我正在使用slim和我创建的组来简化我的路线文件。 但由于一个组应该是非管理员用户的未授权,我想重定向该组中的所有路由,而不是像这样一个接一个地重定向所有路由:

的index.php

{{1}}

如您所见,相同的代码会出现多次,是否可以将其分解?

1 个答案:

答案 0 :(得分:2)

您可以使用route middleware

创建路由中间件并将其添加到变量:

$handleAuthorization = function () {
    if(!(isset($_SESSION["type"]) && $_SESSION["type"] == "admin")) {
        $app = \Slim\Slim::getInstance();
        $app->redirect($app->urlFor('indexAdmin'));
    }
};

使用该路由中间件变量创建路由:

$app->get('/', function (){
    echo "Home!!";
})->name('indexAdmin');

$app->group('/Admin', $handleAuthorization, function () use ($app) { // crée un "groupe d'URL"

    $app->get('/users', function () use ($app){
        $ctrl = new UserController();
        $ctrl->listing($app);
    });


    $app->get('/users2', function () use ($app){
        $ctrl = new UserController();
        $ctrl->listing($app);
    });
});