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 | |
Derek Jones | af8da30 | 2011-10-05 17:40:07 -0500 | [diff] [blame] | 20 | $this->load->helper('url'); |
| 21 | $this->load->library('session'); |
| 22 | $this->config->item('base_url'); |
| 23 | // etc. |
Derek Jones | 8ede1a2 | 2011-10-05 13:34:52 -0500 | [diff] [blame] | 24 | |
| 25 | $this, however, only works within your controllers, your models, or your |
| 26 | views. If you would like to use CodeIgniter's classes from within your |
| 27 | own custom classes you can do so as follows: |
| 28 | |
| 29 | First, assign the CodeIgniter object to a variable:: |
| 30 | |
| 31 | $CI =& get_instance(); |
| 32 | |
| 33 | Once you've assigned the object to a variable, you'll use that variable |
| 34 | *instead* of $this:: |
| 35 | |
Derek Jones | af8da30 | 2011-10-05 17:40:07 -0500 | [diff] [blame] | 36 | $CI =& get_instance(); |
| 37 | |
| 38 | $CI->load->helper('url'); |
| 39 | $CI->load->library('session'); |
| 40 | $CI->config->item('base_url'); |
| 41 | // etc. |
Derek Jones | 8ede1a2 | 2011-10-05 13:34:52 -0500 | [diff] [blame] | 42 | |
| 43 | .. note:: You'll notice that the above get_instance() function is being |
| 44 | passed by reference:: |
| 45 | |
Derek Jones | af8da30 | 2011-10-05 17:40:07 -0500 | [diff] [blame] | 46 | $CI =& get_instance(); |
Derek Jones | 8ede1a2 | 2011-10-05 13:34:52 -0500 | [diff] [blame] | 47 | |
| 48 | This is very important. Assigning by reference allows you to use the |
| 49 | original CodeIgniter object rather than creating a copy of it. |