How does codeigniter's load work?

笑着哭i 提交于 2019-12-05 05:41:45

The loading, as @yi_H correctly pointed out, lasts for all the current script lifetime. I.E. when you're calling a controller's method, the resource is loaded. If you call the same resource inside another method, that isn't available anymore.

That happens because controller are initialized at each request, so when you access index.php/mycontroller/method1 the controller is initialized (you can enable logs and see this clearly). In your method you load, say, the html helper. If you then access index.php/mycontroller/method2, and it also requires the html helper, but you didn't load it intro the method, you will get an error of function not found.

So, basically, if you want to have the same resource always available you have 3 choices:

  1. autoload it in application/config/autoloader.php
  2. load it at every request, i.e. inside each method that will be using that resource
  3. put it inside the controller's constructor, so to have it always initialized at each request.

It's more or less the same as autoloading, except that it can work only for the controller which you put the constructor in, so you get a benefit when you don't want something to be loaded at EACH controller (like when you use autoloading) but only on a few. In order to use this last method, remember to CALL THE PARENT CONSTRUCTOR inside your controller (like you do normally with models):

function __construct()
{
  parent::__construct();
  $this->load->library('whateveryouwant');
}

It stays there till the end of the time (that is, when your script finishes and the universe collapses)

nvcnvn

To load something when writing your own model or helper, for example:

$ci = get_instance();
$ci->load->library('user_agent');
$ci->load->database();

About all the other question, I think you should load what you need for each Controller.

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