003-ci using CodeIgniter resources in your class library

Source: Internet
Author: User
Tags codeigniter

Use the get_instance () function in your class library to access the native resources of CodeIgniter, which returns the CodeIgniter super object.

Typically, in your controller method you will use the $this to invoke all available CodeIgniter methods:


$this->load->helper (' url '), $this->load->library (' Session '), $this->config->item (' Base_url '); /etc.

But $this can only be used directly in your controller, model, or view, if you want to use the CodeIgniter class in your own class, you can do the following:

First, assign the CodeIgniter object to a variable:

$CI =& get_instance ();

Once you have assigned the CodeIgniter object to a variable, you can use this variable to Replace $this

$CI =& get_instance (); $CI->load->helper (' url '); $CI->load->library (' Session '); $CI->config-> Item (' Base_url ');//etc.


Annotations:

You will see that the get_instance () function above is passed by reference:


$CI =& get_instance ();

It is very important that the reference assignment allows you to use the original CodeIgniter object instead of creating a copy.


If the class library is a class, then we'd better use the OOP principle, so, in order for all methods in the class to use the CodeIgniter Super object, it is recommended to assign it to a property:

Class Example_library {    protected $CI;    We'll use a constructor, as 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 ()    {        echo $this->ci->config->item (' Base_url ');}    }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.