代码点火器延迟加载库/模型/等


CodeIgniter lazy-loading libraries/models/etc

在编写CodeIgniter应用程序时,我的控制器操作往往以以下几行开头:

    $this->load->model('abc_model');
    $this->load->library('ijk');

然后(只是为了完整起见)它们按如下方式使用:

    $this->abc_model->fetch_123();
    $this->ijk->do_something();

扩展MY_Controller以便可以

执行以下操作会不会有什么太大的错误?
    $this->model('zbc_model')->fetch_stuff();
    $this->library('ijk')->do_something();

优点:

  1. 类在实际使用之前不会加载
  2. 不需要使用 config/autoload.php 自动加载任何类
  3. 稍微干净的代码(可以说)

缺点:

  1. 每次访问都需要一个额外的方法调用(通常只返回已加载的实例)
  2. 稍微混乱的代码(可以说)

使用 Phil Sturge 的技术,将其添加到您的应用程序/配置/配置中.php

/*
| -------------------------------------------------------------------
|  Native Auto-load
| -------------------------------------------------------------------
| 
| Nothing to do with cnfig/autoload.php, this allows PHP autoload to work
| for base controllers and some third-party libraries.
|
*/
function __autoload($class)
{
 if(strpos($class, 'CI_') !== 0)
 {
  @include_once( APPPATH . 'core/'. $class . EXT );
 }
}