Codeigniter:我怎么知道模型是否已经加载?

Zak*_*ziz 7 php model codeigniter class

是否有我可以用来判断某个模型是否已加载的本机codeigniter函数?可以使用php class_exists()来判断模型是否已经加载?

Max*_*rin 13

我很想扩展CI_Loader核心课程.(参见扩展核心类)

class MY_Loader extends CI_Loader {

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

    /**
     * Returns true if the model with the given name is loaded; false otherwise.
     *
     * @param   string  name for the model
     * @return  bool
     */
    public function is_model_loaded($name) 
    {
        return in_array($name, $this->_ci_models, TRUE);
    }
}
Run Code Online (Sandbox Code Playgroud)

您将使用以下内容检查给定的模型:

$this->load->is_model_loaded('foobar');
Run Code Online (Sandbox Code Playgroud)

该策略已经被CI_Loader班级使用.

此解决方案支持CI的模型命名功能,其中模型可以具有与模型类本身不同的名称.该class_exists解决方案不支持该功能,但如果您不重命名模型,则应该可以正常工作.

注意:如果您更改了subclass_prefix配置,则可能MY_不再适用.


Ter*_*Lin 8

最简单的解决方案是使用PHP函数class_exists

http://php.net/manual/en/function.class-exists.php

例如.如果要检查是否已定义Post_model.

$this->load->model('post_model');

/*

     a lot of code

*/

if ( class_exists("Post_model") ) {
    // yes
}
else {
    // no
}
Run Code Online (Sandbox Code Playgroud)

最简单的是最好的......