blob: 4d6e8366c6adfbbb461801f4dd41c52fb4f7df32 [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
Derek Jonese69b4562011-10-05 17:30:50 -050041in it::
Derek Jones8ede1a22011-10-05 13:34:52 -050042
Derek Jonese69b4562011-10-05 17:30:50 -050043 <?php
44 class Blog extends CI_Controller {
45
46 public function index()
47 {
48 echo 'Hello World!';
49 }
50 }
51 ?>
52
Derek Jones8ede1a22011-10-05 13:34:52 -050053Then save the file to your application/controllers/ folder.
54
55Now visit the your site using a URL similar to this::
56
57 example.com/index.php/blog/
58
59If you did it right, you should see Hello World!.
60
61Note: Class names must start with an uppercase letter. In other words,
62this is valid::
63
Derek Jonese69b4562011-10-05 17:30:50 -050064 <?php
65 class Blog extends CI_Controller {
66
67 }
68 ?>
69
Derek Jones8ede1a22011-10-05 13:34:52 -050070
71This is **not** valid::
72
Derek Jonese69b4562011-10-05 17:30:50 -050073 <?php
74 class blog extends CI_Controller {
75
76 }
77 ?>
Derek Jones8ede1a22011-10-05 13:34:52 -050078
79Also, always make sure your controller extends the parent controller
80class so that it can inherit all its functions.
81
82Functions
83=========
84
85In the above example the function name is index(). The "index" function
86is always loaded by default if the **second segment** of the URI is
87empty. Another way to show your "Hello World" message would be this::
88
89 example.com/index.php/blog/index/
90
91**The second segment of the URI determines which function in the
92controller gets called.**
93
Derek Jonese69b4562011-10-05 17:30:50 -050094Let's try it. Add a new function to your controller::
Derek Jones8ede1a22011-10-05 13:34:52 -050095
Derek Jonese69b4562011-10-05 17:30:50 -050096 <?php
97 class Blog extends CI_Controller {
98
99 public function index()
100 {
101 echo 'Hello World!';
102 }
103
104 public function comments()
105 {
106 echo 'Look at this!';
107 }
108 }
109 ?>
110
Derek Jones8ede1a22011-10-05 13:34:52 -0500111Now load the following URL to see the comment function::
112
113 example.com/index.php/blog/comments/
114
115You should see your new message.
116
117Passing URI Segments to your Functions
118======================================
119
120If your URI contains more then two segments they will be passed to your
121function as parameters.
122
123For example, lets say you have a URI like this::
124
125 example.com/index.php/products/shoes/sandals/123
126
127Your function will be passed URI segments 3 and 4 ("sandals" and "123")::
128
Derek Jonese69b4562011-10-05 17:30:50 -0500129 <?php
130 class Products extends CI_Controller {
131
132 public function shoes($sandals, $id)
133 {
134 echo $sandals;
135 echo $id;
136 }
137 }
138 ?>
Derek Jones8ede1a22011-10-05 13:34:52 -0500139
140.. important:: If you are using the :doc:`URI Routing <routing>`
141 feature, the segments passed to your function will be the re-routed
142 ones.
143
144Defining a Default Controller
145=============================
146
147CodeIgniter can be told to load a default controller when a URI is not
148present, as will be the case when only your site root URL is requested.
149To specify a default controller, open your application/config/routes.php
150file and set this variable::
151
152 $route['default_controller'] = 'Blog';
153
154Where Blog is the name of the controller class you want used. If you now
155load your main index.php file without specifying any URI segments you'll
156see your Hello World message by default.
157
158Remapping Function Calls
159========================
160
161As noted above, the second segment of the URI typically determines which
162function in the controller gets called. CodeIgniter permits you to
163override this behavior through the use of the _remap() function::
164
Derek Jonese69b4562011-10-05 17:30:50 -0500165 public function _remap()
166 {
167 // Some code here...
168 }
Derek Jones8ede1a22011-10-05 13:34:52 -0500169
170.. important:: If your controller contains a function named _remap(),
171 it will **always** get called regardless of what your URI contains. It
172 overrides the normal behavior in which the URI determines which function
173 is called, allowing you to define your own function routing rules.
174
175The overridden function call (typically the second segment of the URI)
176will be passed as a parameter to the _remap() function::
177
Derek Jonese69b4562011-10-05 17:30:50 -0500178 public function _remap($method)
179 {
180 if ($method == 'some_method')
181 {
182 $this->$method();
183 }
184 else
185 {
186 $this->default_method();
187 }
188 }
Derek Jones8ede1a22011-10-05 13:34:52 -0500189
190Any extra segments after the method name are passed into _remap() as an
191optional second parameter. This array can be used in combination with
192PHP's `call_user_func_array <http://php.net/call_user_func_array>`_
193to emulate CodeIgniter's default behavior.
194
195::
196
Derek Jonese69b4562011-10-05 17:30:50 -0500197 public function _remap($method, $params = array())
198 {
199 $method = 'process_'.$method;
200 if (method_exists($this, $method))
201 {
202 return call_user_func_array(array($this, $method), $params);
203 }
204 show_404();
205 }
Derek Jones8ede1a22011-10-05 13:34:52 -0500206
207Processing Output
208=================
209
210CodeIgniter has an output class that takes care of sending your final
211rendered data to the web browser automatically. More information on this
212can be found in the :doc::doc:`Views <views>` and `Output
213class <../libraries/output>` pages. In some cases, however, you
214might want to post-process the finalized data in some way and send it to
215the browser yourself. CodeIgniter permits you to add a function named
216_output() to your controller that will receive the finalized output
217data.
218
219.. important:: If your controller contains a function named _output(),
220 it will **always** be called by the output class instead of echoing the
221 finalized data directly. The first parameter of the function will
222 contain the finalized output.
223
224Here is an example::
225
Derek Jonese69b4562011-10-05 17:30:50 -0500226 public function _output($output)
227 {
228 echo $output;
229 }
Derek Jones8ede1a22011-10-05 13:34:52 -0500230
Derek Jonese69b4562011-10-05 17:30:50 -0500231.. note:: Please note that your _output() function will receive the data in its
232 finalized state. Benchmark and memory usage data will be rendered, cache
233 files written (if you have caching enabled), and headers will be sent
234 (if you use that :doc:`feature <../libraries/output>`) before it is
235 handed off to the _output() function.
236 To have your controller's output cached properly, its _output() method
237 can use::
Derek Jones8ede1a22011-10-05 13:34:52 -0500238
Derek Jonese69b4562011-10-05 17:30:50 -0500239 if ($this->output->cache_expiration > 0)
240 {
241 $this->output->_write_cache($output);
242 }
Derek Jones8ede1a22011-10-05 13:34:52 -0500243
Derek Jonese69b4562011-10-05 17:30:50 -0500244 If you are using this feature the page execution timer and memory usage
245 stats might not be perfectly accurate since they will not take into
246 acccount any further processing you do. For an alternate way to control
247 output *before* any of the final processing is done, please see the
248 available methods in the :doc:`Output Class <../libraries/output>`.
Derek Jones8ede1a22011-10-05 13:34:52 -0500249
250Private Functions
251=================
252
253In some cases you may want certain functions hidden from public access.
254To make a function private, simply add an underscore as the name prefix
255and it will not be served via a URL request. For example, if you were to
256have a function like this::
257
Derek Jonese69b4562011-10-05 17:30:50 -0500258 private function _utility()
259 {
260 // some code
261 }
Derek Jones8ede1a22011-10-05 13:34:52 -0500262
263Trying to access it via the URL, like this, will not work::
264
265 example.com/index.php/blog/_utility/
266
267Organizing Your Controllers into Sub-folders
268============================================
269
270If you are building a large application you might find it convenient to
271organize your controllers into sub-folders. CodeIgniter permits you to
272do this.
273
274Simply create folders within your application/controllers directory and
275place your controller classes within them.
276
277.. note:: When using this feature the first segment of your URI must
278 specify the folder. For example, lets say you have a controller located
279 here::
280
281 application/controllers/products/shoes.php
282
283 To call the above controller your URI will look something like this::
284
285 example.com/index.php/products/shoes/show/123
286
287Each of your sub-folders may contain a default controller which will be
288called if the URL contains only the sub-folder. Simply name your default
289controller as specified in your application/config/routes.php file
290
291CodeIgniter also permits you to remap your URIs using its :doc:`URI
292Routing <routing>` feature.
293
294Class Constructors
295==================
296
297If you intend to use a constructor in any of your Controllers, you
298**MUST** place the following line of code in it::
299
300 parent::__construct();
301
302The reason this line is necessary is because your local constructor will
303be overriding the one in the parent controller class so we need to
304manually call it.
305
306::
307
Derek Jonese69b4562011-10-05 17:30:50 -0500308 <?php
309 class Blog extends CI_Controller {
310
311 public function __construct()
312 {
313 parent::__construct();
314 // Your own constructor code
315 }
316 }
317 ?>
Derek Jones8ede1a22011-10-05 13:34:52 -0500318
319Constructors are useful if you need to set some default values, or run a
320default process when your class is instantiated. Constructors can't
321return a value, but they can do some default work.
322
323Reserved Function Names
324=======================
325
326Since your controller classes will extend the main application
327controller you must be careful not to name your functions identically to
328the ones used by that class, otherwise your local functions will
329override them. See :doc:`Reserved Names <reserved_names>` for a full
330list.
331
332That's it!
333==========
334
335That, in a nutshell, is all there is to know about controllers.