To check If a user is logged in I need to pull off a pretty long if-statement and then redirect the user depending if the开发者_如何学C user is logged in or not. I think a custom function like
if (logged_in()) { redirect }
Would be more appropriative. But building a library for one function seems unnecessary to me. What should I do?
I need to pull off a pretty long if-statement, but building a library for one function seems unnecessary
It's not at all "unnecessary", neither is it strictly "necessary", but it's probably a good idea to create a library/class for this.
If you have a lot of logic you need to work with, "a pretty long if-statement" for example, using a class can help you break this down into smaller pieces and make the logic more manageable. If you only need to call one public method of the class, like $this->auth->is_logged_in()
, there's nothing wrong with that, then you can create a small helper file or wrapper function to call the method, and put the redirect logic there instead of the class. Something like this perhaps:
// Make sure your "auth" library is autoloaded or load it here
function logged_in($redirect = TRUE)
{
$CI =& get_instance();
$logged_in = $CI->auth->is_logged_in();
// Redirect the user...
if ( ! $logged_in AND $redirect)
{
redirect('somewhere/else/');
}
// Or just check if they are logged in
return $logged_in;
}
Using a class/library has many benefits, and with something as complicated as user authorization you will benefit greatly from taking advantage of it, especially once your project starts to expand and you need more utility.
Although helpers are usually preserved for decoupled functions that have nothing to do with your app, I think in this case they are appropriate. Simply create a helper function called is_logged_in
.
To learn more about helpers, visit the Docs:
http://codeigniter.com/user_guide/general/helpers.html
精彩评论