duanbi1888 2014-06-21 15:15
浏览 50
已采纳

PHP / Kohana - 避免重复代码来检查用户是否已登录

I am a newbie to PHP/Kohana application development.

In the web app i am developing , whenever a new request come to the controller i am required to check if the user is logged-in or is he having sufficient privileges to commit the action he requested. Since my application have different category of members(having different degree of authority), every controller method ends up having multitude of if/else branches. the code is repeated in other controller methods as well.

Is there any suggested way to centralize these calls and to avoid code repetition? I mean is the only way to achieve this by writing a method to encompass all the user session code ? or am i missing any functionality that is baked into the PHP/Kohana which is already dealing this scenario?

eg:-

if (Auth::instance()->logged_in('commentator')) {

// do something here.

}
else if (Auth:instance()->logged_in('admin')){

// do something here.

}
else if (Auth:instance()->logged_in('reviewer')){

// do something here.

} 
  • 写回答

1条回答 默认 最新

  • douyu0852 2014-06-22 03:08
    关注

    Create a controller named Controller_Authenticated with some code like this:

    protected $login_level;
    
    public function before()
    {
        parent::before();
    
        if (Auth::instance()->logged_in('commentator')) {
            $this->login_level = 'commentator';
        }
        elseif (Auth:instance()->logged_in('admin')){
            $this->login_level = 'admin';
        }
        elseif (Auth:instance()->logged_in('reviewer')){
            $this->login_level = 'reviewer';
        }
        else {
            // Redirect to login page here, or display a "you are not logged in" message
        }
    }
    

    Then, have your other controllers extend Controller_Authenticated instead of just Controller. Then you can check the value of parent::$login_level to see what kind of user this is.

    That way, all of your login-checking code is in one place, and checking what kind of user you are is done automatically when the controller loads (before the action is called).

    The Kohana documentation has almost exactly this example for using a before method to handle login stuff.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀