When a user is logged into my CodeIgniter application, I need a list of profiles that they have to be in the menu on every page they visit. Rather than call the model function on every single method in my application like so:
if ($this->users_model->is_logged_in())
{
$data->profiles = $this->profiles_model->get_profiles();
}
$this->load->vars($data);
Is there a better way to do this? I considered the option of extending the CI_Controller class like this also but could not determine how best to pass the variable onto the actual method that will need the information.
class MY_Controller extends CI_Controller
{
public function __construct()
{
// Alternatively these could be auto-loaded
$this->load->model(array('profiles_model', 'users_model'));
if ($this->users_model->is_logged_in())
{
$data->profiles = $this->profiles_model->get_profiles();
}
}
}
My concern lies with best practice, best performance and best ability to cache (if this is even possible).
If I have anything that I need on all pages I do the following.
The reason I do this, is the because if you need it on many different controllers then having it in one easily accessible place is very handy. When you need to maintain your code it will make it a lot easier too. For example, if you want to add in caching then you can just add that code into that single function instead of having to change it in every controller.
Infact, in your specific case, I actually created my own session class to extend the CI Session. As a very basic example (I also use sessions in database for this):
This way, since you are probably storing this information in sessions, it makes a lot of sense to keep that information together.