使用 slim 条件重定向整个组

redirect a whole group on condition with slim

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

index.php

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

    $app->get('/users', function () use ($app){
        if(isset($_SESSION["type"]) && $_SESSION["type"] == "admin") {
            $ctrl = new UserController();
            $ctrl->listing($app);
        }else{
            $app->redirect($app->urlFor('indexAdmin'));
        }
    })


    $app->get('/users', function () use ($app){
        if(isset($_SESSION["type"]) && $_SESSION["type"] == "admin") {
            $ctrl = new UserController();
            $ctrl->listing($app);
        }else{
            $app->redirect($app->urlFor('indexAdmin'));
        }
    })

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

您可以使用 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);
    });
});