CodeIgniter lazy-loading libraries/models/etc

混江龙づ霸主 提交于 2019-12-10 10:54:01

问题


When writing CodeIgniter applications my controller actions tend to begin with a few lines as below:

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

And then (just for completeness) they're used as follows:

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

Would there be anything too wrong about extending MY_Controller so that the following was possible?

    $this->model('zbc_model')->fetch_stuff();
    $this->library('ijk')->do_something();

Pros:

  1. Classes aren't loaded until they're actually used
  2. Wouldn't need to auto-load any classes using config/autoload.php
  3. Slightly cleaner code (arguably)

Cons:

  1. An extra method call for every access (generally just returning the already loaded instance though)
  2. Slightly messier code (arguably)

回答1:


Use Phil Sturgeon's technique, add this to your application/config/config.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 );
 }
}


来源:https://stackoverflow.com/questions/6011271/codeigniter-lazy-loading-libraries-models-etc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!