Derek Jones | 8ede1a2 | 2011-10-05 13:34:52 -0500 | [diff] [blame] | 1 | ########################## |
| 2 | Creating Ancillary Classes |
| 3 | ########################## |
| 4 | |
| 5 | In some cases you may want to develop classes that exist apart from your |
| 6 | controllers but have the ability to utilize all of CodeIgniter's |
| 7 | resources. This is easily possible as you'll see. |
| 8 | |
| 9 | get_instance() |
| 10 | =============== |
| 11 | |
| 12 | **Any class that you instantiate within your controller functions can |
| 13 | access CodeIgniter's native resources** simply by using the |
| 14 | get_instance() function. This function returns the main CodeIgniter |
| 15 | object. |
| 16 | |
| 17 | Normally, to call any of the available CodeIgniter functions requires |
| 18 | you to use the $this construct:: |
| 19 | |
| 20 | $this->load->helper('url'); $this->load->library('session'); $this->config->item('base_url'); etc. |
| 21 | |
| 22 | $this, however, only works within your controllers, your models, or your |
| 23 | views. If you would like to use CodeIgniter's classes from within your |
| 24 | own custom classes you can do so as follows: |
| 25 | |
| 26 | First, assign the CodeIgniter object to a variable:: |
| 27 | |
| 28 | $CI =& get_instance(); |
| 29 | |
| 30 | Once you've assigned the object to a variable, you'll use that variable |
| 31 | *instead* of $this:: |
| 32 | |
| 33 | $CI =& get_instance(); $CI->load->helper('url'); $CI->load->library('session'); $CI->config->item('base_url'); etc. |
| 34 | |
| 35 | .. note:: You'll notice that the above get_instance() function is being |
| 36 | passed by reference:: |
| 37 | |
| 38 | $CI =& get_instance(); |
| 39 | |
| 40 | This is very important. Assigning by reference allows you to use the |
| 41 | original CodeIgniter object rather than creating a copy of it. |