Usage Analysis of Subsidiary Classes in CI Framework

  • 2021-11-10 09:09:33
  • OfStack

This article illustrates the use of satellite classes in CI framework. Share it for your reference, as follows:

Sometimes, you may want to create a new class outside your controller, but at the same time, you want these classes to access CodeIgniter resources

Any class initialized in your controller method can simply pass the get_instance() Function to access CodeIgniter resources. This function returns 1 CodeIgniter object.

Generally speaking, calling methods of CodeIgniter requires using $this


$this->load->helper('url');
$this->load->library('session');
$this->config->item('base_url');

But $this Can only be used in your controller, model, or view. If you want to use the CodeIgniter class in your own class, you can do this as follows:

First, assign the CodeIgniter object to a variable:


$CI =& get_instance();

1 Once you assign an CodeIgniter object to a variable, you can use this variable instead $this


$CI =& get_instance();
$CI->load->helper('url');
$CI->load->library('session');
$CI->config->item('base_url');

If you use ` ` in a class get_instance() The best way to do this is to assign it to a property so that you don't have to call it in every method get_instance() It's over.

For example:


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, foo() And bar() Method can work normally after initializing the Example class, instead of calling it in each method get_instance() Function.

More readers interested in CodeIgniter can check the topics on this site: "codeigniter Introduction Tutorial", "CI (CodeIgniter) Framework Advanced Tutorial", "php Excellent Development Framework Summary", "ThinkPHP Introduction Tutorial", "ThinkPHP Common Methods Summary", "Zend FrameWork Framework Introduction Tutorial", "php Object-Oriented Programming Introduction Tutorial", "php+mysql Database Operation Introduction Tutorial" and "php Common Database Operation Skills Summary"

I hope this article is helpful to the PHP programming based on CodeIgniter framework.


Related articles: