CodeIgniter中的模型/库延迟加载


Model/library lazy load in CodeIgniter

我必须在CodeIgniter:中这样做

$this->load->model('Test_model');
$this->Test_model->....

我只想要:

$this->Test_model->...

我不想自动加载所有模型,我想按需加载模型。如何将"延迟加载"逻辑添加到CI_Controller__get()?我应该添加什么逻辑?

提前感谢!

PS请不要把我的问题和CodeIgniter懒惰加载库/模型等混淆——我们有不同的目标。

当前解决方案

像一样更新您的CI_Controller::__construct()(路径system/core/Controller/

foreach (is_loaded() as $var => $class)
{
        $this->$var = '';
        $this->$var =& load_class($class);
}
$this->load = '';
$this->load =& load_class('Loader', 'core');

然后在CI_Controller类中添加一个新方法

public function &__get($name)
{
//code here from @Twisted1919's answer
}

下面的内容似乎在ci中不起作用(事实上,魔术方法不起作用),我将把它留在这里作为其他人的参考

好吧,在您的特定情况下,这应该可以做到(在您的MY_Controller中):

public function __get($name)
{
    if (!empty($this->$name) && $this->$name instanceof CI_Model) {
        return $this->$name;
    }
    if (is_file(APPPATH.'models/'.$name.'.php')) {
        $this->load->model($name);
        return $this->$name;
    }
}

L.E,第二次尝试:

public function __get($name)
{
    if (isset($this->$name) && $this->$name instanceof CI_Model) {
        return $this->$name;
    }
    if (is_file($modelFile = APPPATH.'models/'.$name.'.php')) {
        require_once ($modelFile);
        return $this->$name = new $name();
    }
}

但是,您还需要注意助手、库等。