Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does codeigniter's load work?

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?

like image 789
Vejto Avatar asked Jul 09 '11 09:07

Vejto


1 Answers

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');
}
like image 161
Damien Pirsy Avatar answered Sep 27 '22 22:09

Damien Pirsy