Reputation: 1087
I've recently started to learn OOP and Codeigniter. I've set up 2 new files in core; MY_Controller.php extending CI_Controller and MY_Model.php extending CI_Model. These files are both working, i'm able to call their methods in various controllers and models. However, I have a method in MY_Controller that checks if a user's logged in, if so it calls a method from MY_Model that updates the last active field in the user table. This method is working when I call it from say Login_model, but when I call it from MY_Controller it passes an error:
Call to undefined method Feed::update_last_active()
Why is this? I'm trying to call a core model from my core controller, should I not be doing this? Below is my code.
MY_Controller.php:
class MY_Controller extends CI_Controller{
public function __construct(){
parent::__construct();
}
/**
* Check if the users sessions logged in
*/
public function logged_in(){
//Check the flag logged_in exists in the session
if ($this->session->userdata('logged_in')){
//Update the last active field in the user db
$this->update_last_active($this->session->userdata('user_id'));
return true;
} else {
return false;
}
}
}
MY_Model.php:
class MY_Model extends CI_Model{
/**
* Updates users last active
*/
public function update_last_active($id){
$this->db->where('id', $id);
$this->db->update('users', array('last_active' => date('Y-m-d H:i:s')));
}
}
MY_Controller updated to @Tiger response (Returns Call to undefined method CI_Loader::update_last_active()
):
public function logged_in(){
//Check the flag logged_in exists in the session
if ($this->session->userdata('logged_in')){
//Load my model
$my_model = $this->load->model('MY_Model');
//Update the last active field in the user db
$my_model->update_last_active($this->session->userdata('user_id'));
return true;
} else {
return false;
}
}
Upvotes: 1
Views: 18132
Reputation: 408
Controller file:
public function __construct(){
parent::__construct();
$this->load->model('My_Model'); //Load the Model here
}
public function logged_in(){
if ($this->session->userdata('logged_in')){
//Now Load Only Model Method
$my_model = $this->MY_Model->update_last_active();
$my_model->update_last_active($this->session->userdata('user_id'));
return true;
} else {
return false;
}
}
Upvotes: 3
Reputation: 182
You didn't load the model in the controller, load the model in my_controller
public function __construct(){
parent::__construct();
//load the model
$this->load->model('My_Model');
}
This should solve the issue. logged_in function too have some errors, try loading the model in the _construct() first
Upvotes: 2