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?
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:
- autoload it in application/config/autoloader.php
- load it at every request, i.e. inside each method that will be using that resource
- 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)
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.
精彩评论