Codeigniter Create Ancillary Classes
In some cases, you will need to develop categories that exist with the exception of your controllers however have the power to utilize all of CodeIgniter’s resources.
This is easily possible as you’ll see.
Returns: | Reference to your controller’s instance |
Return type: | CI_Controller |
Any category that you simply instantiate at intervals your controller strategies will access CodeIgniter’s native resources just by exploitation the get_instance() perform.
This function returns the main CodeIgniter object.
Normally, to decide any of the offered strategies, CodeIgniter needs you to use the $this construct:
<?php
$this->load->helper('url');
$this->load->library('session');
$this->config->item('base_url');
$this, however, solely works among your controllers, your models, or your views.
If you'd wish to use CodeIgniter’s categories from among your own custom categories you'll do this as follows:
First, assign the CodeIgniter object to a variable:
Once you’ve appointed the thing to a variable, you’ll use that variable rather than $this:
<?php
$CI =& get_instance();
$CI->load->helper('url');
$CI->load->library('session');
$CI->config->item('base_url');
// etc.
If you’ll be using get_instance() inside another class, then it would be better if you assign it to a property.
This way, you won’t have to be compelled to decision get_instance() in every single technique.
Example:
<?php
class Example {
protected $CI;
// We'll use a constructor, as you can't directly call a function
// from a property definition.
public function __construct()
{
// Assign the CodeIgniter super-object
$this->CI =& get_instance();
}
public function foo()
{
$this->CI->load->helper('url');
redirect();
}
public function bar()
{
$this->CI->config->item('base_url');
}
}
In the above example, both methods foo() and bar() will work after you instantiate the Example class, without the need to call get_instance() in each of them.