views:

210

answers:

2

Hey guys,

I have this private session in one of my controllers that checks if a user is logged in:

    function _is_logged_in() {
 $user = $this->session->userdata('user_data');
 if (!isset($user)) { return false; } else { return true; }
    }

Problem is that I have more than one Controller. How can I use this function in those other controllers? Redefining the function in every Controller isn't very 'DRY'.

Any ideas?

+2  A: 

Put it in a helper and autoload it.

helpers/login_helper.php:

function is_logged_in() {
    // Get current CodeIgniter instance
    $CI =& get_instance();
    // We need to use $CI->session instead of $this->session
    $user = $CI->session->userdata('user_data');
    if (!isset($user)) { return false; } else { return true; }
}

config/autoload.php:

$autoload['helper'] = array('login');

Then in your controller you can call:

is_logged_in();
Rocket
how do I call the session class from outside a class? I'm getting this error with your code: Fatal error: Using $this when not in object context in C:\xampplite\htdocs\mobilehome\application\helpers\login_helper.php on line 4 ... thanks!
Sled
You don't use `$this` in a helper. Please look again at the code in the answer. In helpers (and libraries), to use CodeIgniter functions, you need to get the CodeIgniter instance. `$CI =` does this. Instead of using `$this`, use `$CI`.
Rocket
I see, thanks again!
Sled
You're welcome.
Rocket
+5  A: 

Another option is to create a base controller. Place the function in the base controller and then inherit from this.

To achieve this in CodeIgniter, create a file called MY_Controller.php in the libraries folder of your application.

class MY_Controller extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function is_logged_in()
    {
        $user = $this->session->userdata('user_data');
        return isset($user);
    }
}

Then make your controller inherit from this base controller.

class X extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function do_something()
    {
        if ($this->is_logged_in())
        {
            // User is logged in.  Do something.
        }
    }
}
Stephen Curran
Didn't think of that, I really like the idea. I think it's a bit more practical than using a helper.
Sled
My controller doesn't get detected, i get this error: Fatal error: Class 'MY_Controller' not found in C:\xampplite\htdocs\mobilehome\application\controllers\links.php on line 3 ............ any idea how I can autoload it somewhere? Or should I just include it on top of every controller?
Sled
I think the controllers need constructors. `function __construct(){parent::__construct();}`
Rocket
Sorry Sied. Rocket is right. I had forgotten the constructors. I've updated the answer.
Stephen Curran