I am trying to build my own simple MVC framework, mainly for educational purposes than anything else, I have used CodeIgniter in the past which has provided most of the inspiration for the features I would like to incorporate into my framework.
I would like to build a loader class like CodeIgniters, but I can’t understand how CI loads the classes as if they are properties of the calling class i.e
class Random_Controller{
function __construct(){
$this->load->helper('some_class');
$this->some_class->do_something();
/*
How does CI load some_class as if it were a property of Random_Controller?
I can understand using something like $$class_name = new $class_name();
Or $$this->class_name = new $class_name();
But how can the dynamically named object be used with $this->?
*/
}
}
Hopefully that makes sense…
I am always surprised at how simple things appear with the right explanation. One more question though.
If $load is a reference to an instance of load class, and a record of all loaded classes is kept in an array, we are essentially doing:
$this->loaded_classes[$key]->do_something()?
So how does CI resolve the array to a variable name? I have seen some PHP magic methods that are called when variables do not exist or methods do not exist, would this be done in conjuction with these magic methods? In other words if the $this->some_class property does not exist we search for an element in the array with that key?
If that makes sense..
Uhm, well, let’s start with this: the CI_Controller super class; it’s the one all controllers extends, and acts as the CI superobject all the $this refer to.
CI_Controller acts as a singleton, and during initializing it calls a function,
load_class()(you can find in core/common.php) which works as an autoloader : inside a static array ($_classes) it assignes as index the class name, and as value the class instance:Then the companion
is_loaded()function (in the same file) registers in an array all the function loaded, and is used to check later if the class has already been instantiated or not.Ci_Controller assigns then to its $load property an instance of the Loader class (core/loader.php, by using the above mechanism)
which, in turn, is responsibile for loading all other resources using its own methods: helper(),library(),model() and so on. Have a look at the source for all details, hope you got the picture though
To clarify as per your comment:
would be the same as:
$this->load->helper('helper'),as
$this->loadcontains an instance (by reference) of the Loader class.Then how the helper(),library(),etc methods of the Loader class work would be too much to write here, and beside you can open up the Loader.php file and have a look by yourself.