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

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.

} 

我是PHP / Kohana应用程序开发的新手。 p>

在 我正在开发的web应用程序,每当有新请求到达控制器时,我都需要检查用户是否已登录,或者他是否具有足够的权限来提交他请求的操作。 由于我的应用程序具有不同类别的成员(具有不同程度的权限),因此每个控制器方法最终都具有多个if / else分支。 代码也在其他控制器方法中重复。 p>

是否有任何建议的方法来集中这些调用并避免代码重复? 我的意思是通过编写一个包含所有用户会话代码的方法来实现这一目标的唯一方法是什么? 或者我缺少已经处理这种情况的PHP / Kohana中的任何功能? p>

例如: - p>

  if  (Auth :: instance() - > logged_in('commentator')){
 
 //在这里做点什么。
 
} 
如果(Auth:instance() - > logged_in('admin')  )){
 
 //在这里做点什么。
 
} 
如果(Auth:instance() - > logged_in('reviewer')){
 
 //在这里做点什么。
  
} 
  code>  pre> 
  div>

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.