Accessing CodeIgniter Resources from Library Items
Everything loaded in CodeIgniter is accessable from the CI super object. This is great to keep syntax consistent between Models and Controllers. From within these classes, you can use $this to access loaded resources.
CodeIgniter’s userguide states:
$this, however, only works directly within your controllers, your models, or your views.
Have a look at the code within CI_Model though – or the lack of code!. CI_Model only contains one although very ‘magic’, method:
function __get($key)
{
$CI =& get_instance();
return $CI->$key;
}
PHP’s __get() magic method is called whenever a property is accessed which does not exist. CI_Model directs this request to the CI super object and returns the response.
To allow this behaviour within your custom libraries, create the file CI_Library.php within your application’s /libraries/ folder. Once created, add the following code:
class CI_Library {
public function __get( $insKey ) {
return get_instance()->$insKey;
}
}
The above class is exactly the same as CI_Model (with a few personal preferences) and can be extended in the same way by adding ‘ci_library’ to the libraries config array in autoload.php.
Example:
class Sheep extends CI_Library {
public function baa() {
$this->load->model( 'animal_model' );
}
}
Note: You can move CI_Library into your application’s /core/ folder and remove it from autoload.php by autoloading the class when requested using resource autoloading.
