【问题标题】:redirect a whole group on condition with slim在苗条的条件下重定向整个组
【发布时间】:2015-12-27 22:27:02
【问题描述】:

我正在使用 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'));
        }
    })

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

【问题讨论】:

标签: authentication redirect routes slim


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-06-17
    • 1970-01-01
    • 2021-01-15
    • 2020-05-13
    • 2020-07-06
    • 2019-12-15
    • 2020-04-17
    • 2021-07-04
    • 2021-06-04
    相关资源
    最近更新 更多