延迟加载模型和库中的CI 3 __get魔法控制器方法

时间:2016-02-09 00:26:46

标签: php codeigniter

我正在尝试为CI 3.0.4中的模型+库编写一个延迟加载器

我试图按照以下描述获得以下内容:

Model/library lazy load in CodeIgniter

此代码似乎适用于CI版本2,当我尝试将其应用于CI版本3.0.4时,我收到以下错误。

Severity: Notice

Message: Indirect modification of overloaded property Items::$benchmark has no effect

Filename: core/Controller.php

Line Number: 75


Fatal error: Cannot assign by reference to overloaded object in /Applications/MAMP/htdocs/phppos/PHP-Point-Of-Sale/system/core/Controller.php on line 75

这是我做的:

  1. 创建文件application / core / MY_Controller.php

  2. 创建以下代码:

        //Lazy load based on https://stackoverflow.com/questions/17579449/model-library-lazy-load-in-codeigniter
        function __get($name)
        {
           if (isset($this->$name) && $this->$name instanceof CI_Model) 
            {
                  return $this->$name;
            }
        }
      }
    
  3. 一旦我可以毫无错误地使用它;我将添加我的自定义逻辑来加载正确的模型或库。

    我想在不修改核心的情况下这样做。

1 个答案:

答案 0 :(得分:0)

基于示例,我提出了以下内容,它不需要核心修改,并且可以在CI 3.0.4中使用。它首先尝试加载模型,如果模型不存在,它会尝试加载库。

  1. 创建文件application / core / MY_Controller.php

  2. 将这些内容放入其中。

    <?php
    class MY_Controller extends CI_Controller 
    {
    
        //Lazy loading based on http://stackoverflow.com/questions/17579449/model-library-lazy-load-in-codeigniter
        public function __construct()
        {
            foreach (is_loaded() as $var => $class)
            {
                 $this->$var = '';
            }
    
            $this->load = '';
            parent::__construct();
        }
    
    
        // Lazy load models + libraries....If we can't load a model that we have; then we will try to load library $name
        public function __get($name)
        {
            //Cache models so we only scan model dir once
    
            static $models = FALSE;
            $this->load->helper('file');
    
            if (!$models)
            {
                $model_files = get_filenames(APPPATH.'models', TRUE);
                foreach($model_files as $model_file)
                {
                    $model_relative_name = str_replace('.php','',substr($model_file,strlen(APPPATH.'models'.DIRECTORY_SEPARATOR)));
                    $model_folder = strpos($model_relative_name, DIRECTORY_SEPARATOR) !== FALSE ? substr($model_relative_name,0,strrpos($model_relative_name,DIRECTORY_SEPARATOR)) : '';
                    $model_name = str_replace($model_folder.DIRECTORY_SEPARATOR, '',$model_relative_name);
    
                    $models[$model_name] = $model_folder.'/'.$model_name;
                }
            }
    
            if (isset($models[$name]))
            {
                $this->load->model($models[$name]);
                return $this->$name;
            }
            else //Try a library if we cannot load a model
            {
                $this->load->library($name);
                return $this->$name;
            }
    
            return NULL;
        }
    }