• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How exactly CI instantiates Model and Controller?

#1
[eluser]Unknown[/eluser]
Good day. I would like to ask how CodeIgniter instantiates Model and Controller classes? Does it instantiate them for each request and destroy them after the request? Im just curios how it exactly works. Thanks.

#2
[eluser]PhilTem[/eluser]
To answer your particular question: CI instantiates them for every request, since PHP has no persistence i.e. every object that you will instantiate will be grabbed by the garbage collector after all data was submitted to the client's computer. That said, every request to any of your pages is "new" to CI/your server and it runs through all lines of necessary code.

The general instantiation of models is pretty straight forward as in procedural/non-framework PHP.

As for example loading a model goes like this (taken from ./system/core/Loader.php)

Code:
[...]
if ( ! class_exists('CI_Model'))
{
load_class('Model', 'core');
}

require_once($mod_path.'models/'.$path.$model.'.php');

$model = ucfirst($model);
$CI->$name = new $model();
$this->_ci_models[] = $name;
return;

#3
[eluser]CroNiX[/eluser]
If you would really like to know how it works, trace the code starting with
/system/core/CodeIgniter.php
which is what gets loaded immediately after index.php, which sets paths and some basic settings.

You will learn a heck of a lot more about the framework you are using and it's workflow, which will come in more handy than the docs at times. If you want to efficiently and effectively use it, you need to know how it works inside and out. For instance, if you use caching pages and a cached page exists for the current request, the controller isn't called as it's not needed.

Basically PhilTems explanation is correct, though. Each request is a new request and it starts from scratch. If you autoload models, then they will load on every request along with anything else autoloaded - so use autoload sparingly and only for things that get used all over the place, like the database class or a user model or something. If you load a model in a particular controller that is called, then it will instantiate it.


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.