Saturday, February 16, 2008

The first thing to know

The object being instance as a controller, has references to all the libraries and models who have instanciated as an attribute of the same name in the class.
So if we load the library Email, we have $ this->email is an instance of the class email.

The issue does not end there. Each model also has the same attributes loaded, then we have the code in the controller and the model is similar, as they have the same attributes. So, if we do some code in the controller and we think it is very general and we may need inside another, it's easy to make it a model.

But ... What if we are in a library?
At libraries this attributes are not loaded, but may need access to another library, or a model. For this, we can access the instance of the controller through the "get_instance" function.
For example, within the class we want to validate the email message with the method valid_email the kind of validation. Then:

Function valid_email ($ address)
{
// (& It is important to avoid creating a copy in PHP 4)
$CI =& get_instance();

// If not loaded the library, load it
if (!isset($CI->validation))
{
$CI->load->library('validation');
}

// Call the method
return $CI->validation->valid_email($address);
}

Simple, no?

Still, this follows ...
What if at the view, we want access to a library or model, for example, the validation to retrieve messages?

The views can also access as $ this->validation to the same object that the controller or models.
Internally, this is accomplished by assigning these instances to Class Loader, where the views are loaded.

No comments: