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 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示