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 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果