美文网首页
beforeAction 中使用 $this->redirect

beforeAction 中使用 $this->redirect

作者: jacky_8897 | 来源:发表于2019-10-25 22:39 被阅读0次

    摘自:http://www.dodobook.net/php/3486

    beforeAction中做了是否登录的判断,未登录则跳转到登录页面,所有的类继承的这个BaseController。
    ···
    <?php

    //控制器之前先判断用户是否有权限
    public function beforeAction($action) {
         
        //得到当前访问的路由
        $access = '/hello/dodo';
         
        //如果该路由是永远被允许的
        if (in_array($access, $this->allowedAccess())) {
            return true;
        }else{      //用户登录页面
            if(\Yii::$app->user->isGuest){        //如果用户未登录
                $this->redirect('/site/login');
            //    Yii::$app->response->send();
            //    Yii::$app->end();
            }
        }
    }
    

    ?>
    ···
    在正常情况下,使用 return this->redirect(url);
    ···
    解决方式一:在redirect后面使用send()
    this->redirect(登录页地址)->send();this->redirect(登录页地址l);
    Yii::$app->response->send();

    解决方式二:
    this->redirect(登录页地址); Yii::app->end();

    总结:
    用\Yii::app->end(); \Yii::app->response->send();
    ···
    不管在actionXXX还是init方法都能终止代码,而return只能在action终止代码,是因为在init()里仅仅是代码的执行,return只是代码返回

    相关文章

      网友评论

          本文标题:beforeAction 中使用 $this->redirect

          本文链接:https://www.haomeiwen.com/subject/gfnevctx.html