Moving Data between Controllers and Models - Codeigniter Best Practices

1.1k Views Asked by At

Sorry for the simple question but let's say that I'm using Ion-Auth with Codeigniter to distinguish between logged-in and not logged-in users.

And I have a simple custom Controller that captures the user's ID as such:

class MY_Controller extends CI_Controller {
     function __construct() {
        parent::__construct();
        global $data;
            if($this->ion_auth->logged_in()){
            $data['logged'] = True;
            $data['uid'] = $this->ion_auth->get_user_id();
            $data['username'] = $this->ion_auth->get_username();
        }

        //User is Not Logged in
        else{
            $data['logged'] = False;
        }
    }
}

Then with any of my regular controller I want to spit out a page for logged-in users and not logged-in users as such...

if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Welcome extends MY_Controller {
        {
        global $data;
            if($data['logged']) {
                $this->load->view('logged_in', $data);
                }
            else{
                $this->load->view('not_logged_in', $data);
            }   
        }
}

My question is how should I go about passing the uid to my models? Some of the models are called by the default CI controller that don't call the $this->ion_auth->get_user_id(); function. Should I go into those default controllers and pass the uid to the models or should I call the function $this->ion_auth->get_user_id(); directly within the model?

I apologize for any confusion, I just have a mess of controllers and models that need or don't need the user_id and am trying to avoid having to hard-code each one.

2

There are 2 best solutions below

1
On

You don't need to load the library in the MODEL, MODELS are always called from the CONTROLLERS so you just have to load the Libraries in the Controller, and the functions will be available in the models called from him

So the code

$this->ion_auth->get_user_id()

will work in all models loaded by the controller

2
On

You can do either.

I try hard to send the user_id to the model within an array (just as you have). It makes the models cleaner and easier to read for me.

eg:

  $data['uid'] = $this->ion_auth->get_user_id();
  $model_results = $this->some_model->get_data($data);

But if you want you can access it via the CI instance

Start the model with

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

    $ci =& get_instance();

}

and then I can access the user_id as follows:

 $user_id = $CI->ion_auth->get_user_id();