blob: 8f02df21f3b080902321a8fb69cad9939dd3fed7 [file] [log] [blame]
Derek Jones8ede1a22011-10-05 13:34:52 -05001###########
2Controllers
3###########
4
5Controllers are the heart of your application, as they determine how
6HTTP requests should be handled.
7
8- `What is a Controller? <#what>`_
9- `Hello World <#hello>`_
10- `Functions <#functions>`_
11- `Passing URI Segments to Your Functions <#passinguri>`_
12- `Defining a Default Controller <#default>`_
13- `Remapping Function Calls <#remapping>`_
14- `Controlling Output Data <#output>`_
15- `Private Functions <#private>`_
16- `Organizing Controllers into Sub-folders <#subfolders>`_
17- `Class Constructors <#constructors>`_
18- `Reserved Function Names <#reserved>`_
19
20What is a Controller?
21=====================
22
23A Controller is simply a class file that is named in a way that can be
24associated with a URI.
25
26Consider this URI::
27
28 example.com/index.php/blog/
29
30In the above example, CodeIgniter would attempt to find a controller
31named blog.php and load it.
32
33**When a controller's name matches the first segment of a URI, it will
34be loaded.**
35
36Let's try it: Hello World!
37==========================
38
39Let's create a simple controller so you can see it in action. Using your
40text editor, create a file called blog.php, and put the following code
41in it:
42
43<?php class Blog extends CI_Controller { public function index() { echo
44'Hello World!'; } } ?>
45Then save the file to your application/controllers/ folder.
46
47Now visit the your site using a URL similar to this::
48
49 example.com/index.php/blog/
50
51If you did it right, you should see Hello World!.
52
53Note: Class names must start with an uppercase letter. In other words,
54this is valid::
55
56 <?php class Blog extends CI_Controller { } ?>
57
58This is **not** valid::
59
60 <?php class blog extends CI_Controller { } ?>
61
62Also, always make sure your controller extends the parent controller
63class so that it can inherit all its functions.
64
65Functions
66=========
67
68In the above example the function name is index(). The "index" function
69is always loaded by default if the **second segment** of the URI is
70empty. Another way to show your "Hello World" message would be this::
71
72 example.com/index.php/blog/index/
73
74**The second segment of the URI determines which function in the
75controller gets called.**
76
77Let's try it. Add a new function to your controller:
78
79<?php class Blog extends CI_Controller { public function index() { echo
80'Hello World!'; } public function comments() { echo 'Look at this!'; } }
81?>
82Now load the following URL to see the comment function::
83
84 example.com/index.php/blog/comments/
85
86You should see your new message.
87
88Passing URI Segments to your Functions
89======================================
90
91If your URI contains more then two segments they will be passed to your
92function as parameters.
93
94For example, lets say you have a URI like this::
95
96 example.com/index.php/products/shoes/sandals/123
97
98Your function will be passed URI segments 3 and 4 ("sandals" and "123")::
99
100 <?php class Products extends CI_Controller {     public function shoes($sandals, $id)     {         echo $sandals;         echo $id;     } } ?>
101
102.. important:: If you are using the :doc:`URI Routing <routing>`
103 feature, the segments passed to your function will be the re-routed
104 ones.
105
106Defining a Default Controller
107=============================
108
109CodeIgniter can be told to load a default controller when a URI is not
110present, as will be the case when only your site root URL is requested.
111To specify a default controller, open your application/config/routes.php
112file and set this variable::
113
114 $route['default_controller'] = 'Blog';
115
116Where Blog is the name of the controller class you want used. If you now
117load your main index.php file without specifying any URI segments you'll
118see your Hello World message by default.
119
120Remapping Function Calls
121========================
122
123As noted above, the second segment of the URI typically determines which
124function in the controller gets called. CodeIgniter permits you to
125override this behavior through the use of the _remap() function::
126
127 public function _remap() {     // Some code here... }
128
129.. important:: If your controller contains a function named _remap(),
130 it will **always** get called regardless of what your URI contains. It
131 overrides the normal behavior in which the URI determines which function
132 is called, allowing you to define your own function routing rules.
133
134The overridden function call (typically the second segment of the URI)
135will be passed as a parameter to the _remap() function::
136
137 public function _remap($method) {     if ($method == 'some_method')     {         $this->$method();     }     else     {         $this->default_method();     } }
138
139Any extra segments after the method name are passed into _remap() as an
140optional second parameter. This array can be used in combination with
141PHP's `call_user_func_array <http://php.net/call_user_func_array>`_
142to emulate CodeIgniter's default behavior.
143
144::
145
146 public function _remap($method, $params = array()) {     $method = 'process_'.$method;     if (method_exists($this, $method))     {         return call_user_func_array(array($this, $method), $params);     }     show_404(); }
147
148Processing Output
149=================
150
151CodeIgniter has an output class that takes care of sending your final
152rendered data to the web browser automatically. More information on this
153can be found in the :doc::doc:`Views <views>` and `Output
154class <../libraries/output>` pages. In some cases, however, you
155might want to post-process the finalized data in some way and send it to
156the browser yourself. CodeIgniter permits you to add a function named
157_output() to your controller that will receive the finalized output
158data.
159
160.. important:: If your controller contains a function named _output(),
161 it will **always** be called by the output class instead of echoing the
162 finalized data directly. The first parameter of the function will
163 contain the finalized output.
164
165Here is an example::
166
167 public function _output($output) {     echo $output; }
168
169Please note that your _output() function will receive the data in its
170finalized state. Benchmark and memory usage data will be rendered, cache
171files written (if you have caching enabled), and headers will be sent
172(if you use that :doc:`feature <../libraries/output>`) before it is
173handed off to the _output() function.
174To have your controller's output cached properly, its _output() method
175can use::
176
177 if ($this->output->cache_expiration > 0) {     $this->output->_write_cache($output); }
178
179If you are using this feature the page execution timer and memory usage
180stats might not be perfectly accurate since they will not take into
181acccount any further processing you do. For an alternate way to control
182output *before* any of the final processing is done, please see the
183available methods in the :doc:`Output Class <../libraries/output>`.
184
185Private Functions
186=================
187
188In some cases you may want certain functions hidden from public access.
189To make a function private, simply add an underscore as the name prefix
190and it will not be served via a URL request. For example, if you were to
191have a function like this::
192
193 private function _utility() {   // some code }
194
195Trying to access it via the URL, like this, will not work::
196
197 example.com/index.php/blog/_utility/
198
199Organizing Your Controllers into Sub-folders
200============================================
201
202If you are building a large application you might find it convenient to
203organize your controllers into sub-folders. CodeIgniter permits you to
204do this.
205
206Simply create folders within your application/controllers directory and
207place your controller classes within them.
208
209.. note:: When using this feature the first segment of your URI must
210 specify the folder. For example, lets say you have a controller located
211 here::
212
213 application/controllers/products/shoes.php
214
215 To call the above controller your URI will look something like this::
216
217 example.com/index.php/products/shoes/show/123
218
219Each of your sub-folders may contain a default controller which will be
220called if the URL contains only the sub-folder. Simply name your default
221controller as specified in your application/config/routes.php file
222
223CodeIgniter also permits you to remap your URIs using its :doc:`URI
224Routing <routing>` feature.
225
226Class Constructors
227==================
228
229If you intend to use a constructor in any of your Controllers, you
230**MUST** place the following line of code in it::
231
232 parent::__construct();
233
234The reason this line is necessary is because your local constructor will
235be overriding the one in the parent controller class so we need to
236manually call it.
237
238::
239
240 <?php class Blog extends CI_Controller {        public function __construct()        {             parent::__construct();             // Your own constructor code        } } ?>
241
242Constructors are useful if you need to set some default values, or run a
243default process when your class is instantiated. Constructors can't
244return a value, but they can do some default work.
245
246Reserved Function Names
247=======================
248
249Since your controller classes will extend the main application
250controller you must be careful not to name your functions identically to
251the ones used by that class, otherwise your local functions will
252override them. See :doc:`Reserved Names <reserved_names>` for a full
253list.
254
255That's it!
256==========
257
258That, in a nutshell, is all there is to know about controllers.