开发者

Refactoring a header location function

Should this function be:

check_login_session()
{
   if (!isset[$_SESSION['user_auth']) )
   {
      header('Location: login.php');
   }
   else
   {
      #  check against database here?
      return $_SESSION['user_auth'];开发者_JS百科
   }
}

Or, should a header be send out after the function has been called:

check_login_session()
{
   if (!isset[$_SESSION['user_auth']) )
   {
      return false;
   }
   else
   {
      #  check against database here?
      return $_SESSION['user_auth'];
   }
}

so, when it is called:

if (check_login_session === false)
{
   header('Location: login.php');
}

I know the code does essentially the same thing, but what is the most 'proper way' to refactor this?


I would use the second approach. Generally speaking functions should be something of a black box... you supply arguments and they return a value or modify something by reference, or if they are a method of an object they might modify that objects state or the state of another object. IF you need to take action based on the return value or modified object/argument then that should be done in the main control logic. There are obviously exceptions but this is a general rule for me.

If it were the case that you needed to send additional specific headers and so you wanted to encapsulate that in a function then that would be fine but i would say separate that from the logic checking if its an authenticated session.


The second approach seems more correct and flexible.

If what is $_SESSION['user_auth'] returns false, you would have to check the response anyway.

Renaming the function to something more like is_logged_in may be more readable, and understandable as to what the function does/returns.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜