Authentication 使用slim在条件下重定向整个组

Authentication 使用slim在条件下重定向整个组,authentication,redirect,routes,slim,Authentication,Redirect,Routes,Slim,我正在与slim合作,并为简化我的路由文件创建了组。 但是,由于组对非管理员用户应该是未经授权的,因此我希望重定向该组中的所有路由,而不是像这样逐个重定向所有路由: index.php $app->group('/Admin',function()使用($app){//crée un“groupe d'URL” $app->get('/users',函数()use($app){ 如果(isset($\u会话[“类型”])&&&$\u会话[“类型”]=“管理”){ $ctrl=新用户控制器();

我正在与slim合作,并为简化我的路由文件创建了组。 但是,由于组对非管理员用户应该是未经授权的,因此我希望重定向该组中的所有路由,而不是像这样逐个重定向所有路由:

index.php

$app->group('/Admin',function()使用($app){//crée un“groupe d'URL”
$app->get('/users',函数()use($app){
如果(isset($\u会话[“类型”])&&&$\u会话[“类型”]=“管理”){
$ctrl=新用户控制器();
$ctrl->listing($app);
}否则{
$app->redirect($app->urlFor('indexAdmin'));
}
})
$app->get('/users',函数()use($app){
如果(isset($\u会话[“类型”])&&&$\u会话[“类型”]=“管理”){
$ctrl=新用户控制器();
$ctrl->listing($app);
}否则{
$app->redirect($app->urlFor('indexAdmin'));
}
})
当您看到同一代码多次出现时,是否可以对其进行分解?

您可以使用

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

$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);
    });
});
使用该路由中间件变量创建路由:

$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);
    });
});
这是一条路要走。