0

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 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?

2
  • I assume you've built your own authentication library to get to this stage? In which case you can add an is_logged_in function to that library. Commented Sep 18, 2011 at 8:46
  • No, I haven't. I have been using callback functions to check if username is available, for example at registration. Commented Sep 18, 2011 at 8:49

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Personally, I would name it something like require_login() or remove the redirect from this function, I would always expect something named logged_in() to simply return true or false.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.