Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access model to query database from a helper function?

I am trying to create authentication for my php website. I am using the codeigniter framework. I will have to validate the session in all the pages of my website. So to avoid the code repetition, i am planning to do it in a helper function. Now that my user credentials are in my database i would like to access the model to query the database from the helper function. In a controller class i would have done this by using

$this->load->model('user_model');

Please let me know its equivalent in a helper file. Any kind of suggestion in approach is also appreciated. Thanks in advance.

like image 271
Vinod Avatar asked Jan 04 '10 15:01

Vinod


2 Answers

You will not be able to use $this to access your CI instance in a helper, but CI has a way to do this -

First, you need a reference to your CI instance:

$CI =& get_instance();

Then, if you need to load the model you can do it like so:

$CI->load->model('model_name');

And finally call any function in your model like this:

$CI->model_name->function_name();

Basically, use $CI instead of $this. Hope that helps.

like image 57
thegibson Avatar answered Nov 06 '22 07:11

thegibson


It's not that much code repetition. I'd suggest this approach:

function __construct()
{
    parent::Controller();

    if ($this->auth->is_logged_in() !== TRUE) // "auth" is the authentication library
    {
        redirect('login');
    }
}
like image 25
Cinnamon Avatar answered Nov 06 '22 07:11

Cinnamon