What is the best way to retrieve data from the model that is required on each page in CodeIgniter?

When a user logs into my CodeIgniter application, I need a list of profiles that they should be in the menu on every page that they visit. Instead of calling a model function for each method in my application, for example:

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 extending the CI_Controller class like this, but was unable to determine how best to pass the variable to the actual method, which would need 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 is best practice, better performance and better ability to cache (if possible).

+4
source share
1 answer

If I have everything I need on all pages, I do the following.

  • Add helper .
  • Add a new helper to autoload .
  • Just call your function where you need it.

The reason I do this is because if you need it on many different controllers, then it is very convenient in one easily accessible place. When you need to maintain your code, this will make it a lot easier. For example, if you want to add caching, you can simply add this code to this single function instead of changing it in each controller.

Infact, in your particular case, I actually created my own session class to extend the CI session. As a basic example (I also use sessions in the database ):

 class MY_Session extends CI_Session { public function __construct() { parent::__construct(); } public function login($email, $password) { $CI =& get_instance(); $CI->load->model('usermodel', 'user'); $result = $CI->user->login($email, $password); if($result === false) { return false; } else { $this->set_userdata('email', $result->email); return true; } } public function is_logged_in() { $email = $this->userdata('email'); if(!empty($email)) { return true; } else { return false; } } } 

Thus, since you are likely to store this information in sessions, it makes sense to store this information together.

+1
source

Source: https://habr.com/ru/post/1393586/


All Articles