summaryrefslogtreecommitdiffstats
path: root/user_guide_src/source/general/ancillary_classes.rst
blob: a4befc7b3018f28c1e1901b29fe180f0ef84d8dd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
##########################
Creating Ancillary Classes
##########################

In some cases you may want to develop classes that exist apart from your
controllers but have the ability to utilize all of CodeIgniter's
resources. This is easily possible as you'll see.

get_instance()
==============

.. php:function:: get_instance()

	:returns:	object of class CI_Controller

**Any class that you instantiate within your controller methods can
access CodeIgniter's native resources** simply by using the
``get_instance()`` function. This function returns the main
CodeIgniter object.

Normally, to call any of the available CodeIgniter methods requires
you to use the ``$this`` construct::

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

``$this``, however, only works within your controllers, your models,
or your views. If you would like to use CodeIgniter's classes from
within your own custom classes you can do so as follows:

First, assign the CodeIgniter object to a variable::

	$CI =& get_instance();

Once you've assigned the object to a variable, you'll use that variable
*instead* of ``$this``::

	$CI =& get_instance();

	$CI->load->helper('url');
	$CI->load->library('session');
	$CI->config->item('base_url');
	// etc.

.. note:: You'll notice that the above get_instance() ``function`` is being
	passed by reference::

		$CI =& get_instance();
	
	This is very important. Assigning by reference allows you to use the
	original CodeIgniter object rather than creating a copy of it.

Furthermore, if you'll be using ``get_intance()`` inside anoter class,
then it would be better if you assign it to a property. This way, you
won't need to call ``get_instance()`` in every single method.

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, both methods ``foo()`` and ``bar()`` will work
after you instantiate the Example class, without the need to call
``get_instance()`` in each of them.