Codeigneter:如何从控制器类调用模型方法?

时间:2016-12-02 10:24:57

标签: php codeigniter oop codeigniter-3

我最近开始学习OOP和Codeigniter。我在核心设置了2个新文件; MY_Controller.php扩展CI_Controller和扩展CI_Model的MY_Model.php。这些文件都有效,我可以在各种控制器和模型中调用它们的方法。但是,我在MY_Controller中有一个方法来检查用户是否已登录,如果是,则调用MY_Model中的方法来更新用户表中的最后一个活动字段。当我从Login_model调用它时,此方法正在工作,但是当我从MY_Controller调用它时,它传递了一个错误:

  

调用未定义的方法Feed :: update_last_active()

这是为什么?我试图从我的核心控制器调用核心模型,我不应该这样做吗?以下是我的代码。

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更新为@Tiger响应(返回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;
        }

    }

2 个答案:

答案 0 :(得分:2)

控制器文件:

 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;
        }

    }

答案 1 :(得分:1)

您没有在控制器中加载模型,在my_controller中加载模型

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

         //load the model  
         $this->load->model('My_Model');  

    }

这应该可以解决问题。 logged_in函数也有一些错误,请尝试首先在_construct()中加载模型

相关问题