How does codeigniter's load work?

2019-04-26 17:54发布

I'm having some trouble understanding how codeigniters loading works.

Well first you have the autoload which seems pretty straight forward, it loads everything everytime. So this sounds good to use for the stuff I use all the time.

Second you can load everything inline. But here is my question: How long does it stay loaded?

Let say I load the form validation library in the controller, then I load the model, can I use the form validation in the model or do I have to reload it again? Continuing let say I load a view and another controller, can I use the form validation? Or do I need to load? After a redirect? How about if I load a model or helper instead of a library? Let say I want to use a model inside another model, where do I load that one?

So the basic question, how long or rather how far does the load go before I need to reload?

3条回答
beautiful°
2楼-- · 2019-04-26 18:23

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');
}
查看更多
做自己的国王
3楼-- · 2019-04-26 18:27

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

查看更多
啃猪蹄的小仙女
4楼-- · 2019-04-26 18:31

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.

查看更多
登录 后发表回答