blob: c3c19cc620070ace27d19eeae74e6fe91e39af31 [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
Joseph Wensley5b3ea1a2011-10-06 20:54:32 -04008.. contents:: Page Contents
Derek Jones8ede1a22011-10-05 13:34:52 -05009
10What is a Controller?
11=====================
12
13A Controller is simply a class file that is named in a way that can be
14associated with a URI.
15
16Consider this URI::
17
18 example.com/index.php/blog/
19
20In the above example, CodeIgniter would attempt to find a controller
21named blog.php and load it.
22
23**When a controller's name matches the first segment of a URI, it will
24be loaded.**
25
26Let's try it: Hello World!
27==========================
28
29Let's create a simple controller so you can see it in action. Using your
30text editor, create a file called blog.php, and put the following code
Derek Jonese69b4562011-10-05 17:30:50 -050031in it::
Derek Jones8ede1a22011-10-05 13:34:52 -050032
Derek Jonese69b4562011-10-05 17:30:50 -050033 <?php
34 class Blog extends CI_Controller {
35
36 public function index()
37 {
38 echo 'Hello World!';
39 }
40 }
41 ?>
42
Derek Jones8ede1a22011-10-05 13:34:52 -050043Then save the file to your application/controllers/ folder.
44
45Now visit the your site using a URL similar to this::
46
47 example.com/index.php/blog/
48
49If you did it right, you should see Hello World!.
50
51Note: Class names must start with an uppercase letter. In other words,
52this is valid::
53
Derek Jonese69b4562011-10-05 17:30:50 -050054 <?php
55 class Blog extends CI_Controller {
56
57 }
58 ?>
59
Derek Jones8ede1a22011-10-05 13:34:52 -050060
61This is **not** valid::
62
Derek Jonese69b4562011-10-05 17:30:50 -050063 <?php
64 class blog extends CI_Controller {
65
66 }
67 ?>
Derek Jones8ede1a22011-10-05 13:34:52 -050068
69Also, always make sure your controller extends the parent controller
70class so that it can inherit all its functions.
71
72Functions
73=========
74
75In the above example the function name is index(). The "index" function
76is always loaded by default if the **second segment** of the URI is
77empty. Another way to show your "Hello World" message would be this::
78
79 example.com/index.php/blog/index/
80
81**The second segment of the URI determines which function in the
82controller gets called.**
83
Derek Jonese69b4562011-10-05 17:30:50 -050084Let's try it. Add a new function to your controller::
Derek Jones8ede1a22011-10-05 13:34:52 -050085
Derek Jonese69b4562011-10-05 17:30:50 -050086 <?php
87 class Blog extends CI_Controller {
88
89 public function index()
90 {
91 echo 'Hello World!';
92 }
93
94 public function comments()
95 {
96 echo 'Look at this!';
97 }
98 }
99 ?>
100
Derek Jones8ede1a22011-10-05 13:34:52 -0500101Now load the following URL to see the comment function::
102
103 example.com/index.php/blog/comments/
104
105You should see your new message.
106
107Passing URI Segments to your Functions
108======================================
109
110If your URI contains more then two segments they will be passed to your
111function as parameters.
112
113For example, lets say you have a URI like this::
114
115 example.com/index.php/products/shoes/sandals/123
116
117Your function will be passed URI segments 3 and 4 ("sandals" and "123")::
118
Derek Jonese69b4562011-10-05 17:30:50 -0500119 <?php
120 class Products extends CI_Controller {
121
122 public function shoes($sandals, $id)
123 {
124 echo $sandals;
125 echo $id;
126 }
127 }
128 ?>
Derek Jones8ede1a22011-10-05 13:34:52 -0500129
130.. important:: If you are using the :doc:`URI Routing <routing>`
131 feature, the segments passed to your function will be the re-routed
132 ones.
133
134Defining a Default Controller
135=============================
136
137CodeIgniter can be told to load a default controller when a URI is not
138present, as will be the case when only your site root URL is requested.
139To specify a default controller, open your application/config/routes.php
140file and set this variable::
141
142 $route['default_controller'] = 'Blog';
143
144Where Blog is the name of the controller class you want used. If you now
145load your main index.php file without specifying any URI segments you'll
146see your Hello World message by default.
147
148Remapping Function Calls
149========================
150
151As noted above, the second segment of the URI typically determines which
152function in the controller gets called. CodeIgniter permits you to
153override this behavior through the use of the _remap() function::
154
Derek Jonese69b4562011-10-05 17:30:50 -0500155 public function _remap()
156 {
157 // Some code here...
158 }
Derek Jones8ede1a22011-10-05 13:34:52 -0500159
160.. important:: If your controller contains a function named _remap(),
161 it will **always** get called regardless of what your URI contains. It
162 overrides the normal behavior in which the URI determines which function
163 is called, allowing you to define your own function routing rules.
164
165The overridden function call (typically the second segment of the URI)
166will be passed as a parameter to the _remap() function::
167
Derek Jonese69b4562011-10-05 17:30:50 -0500168 public function _remap($method)
169 {
170 if ($method == 'some_method')
171 {
172 $this->$method();
173 }
174 else
175 {
176 $this->default_method();
177 }
178 }
Derek Jones8ede1a22011-10-05 13:34:52 -0500179
180Any extra segments after the method name are passed into _remap() as an
181optional second parameter. This array can be used in combination with
182PHP's `call_user_func_array <http://php.net/call_user_func_array>`_
183to emulate CodeIgniter's default behavior.
184
185::
186
Derek Jonese69b4562011-10-05 17:30:50 -0500187 public function _remap($method, $params = array())
188 {
189 $method = 'process_'.$method;
190 if (method_exists($this, $method))
191 {
192 return call_user_func_array(array($this, $method), $params);
193 }
194 show_404();
195 }
Derek Jones8ede1a22011-10-05 13:34:52 -0500196
197Processing Output
198=================
199
200CodeIgniter has an output class that takes care of sending your final
201rendered data to the web browser automatically. More information on this
202can be found in the :doc::doc:`Views <views>` and `Output
203class <../libraries/output>` pages. In some cases, however, you
204might want to post-process the finalized data in some way and send it to
205the browser yourself. CodeIgniter permits you to add a function named
206_output() to your controller that will receive the finalized output
207data.
208
209.. important:: If your controller contains a function named _output(),
210 it will **always** be called by the output class instead of echoing the
211 finalized data directly. The first parameter of the function will
212 contain the finalized output.
213
214Here is an example::
215
Derek Jonese69b4562011-10-05 17:30:50 -0500216 public function _output($output)
217 {
218 echo $output;
219 }
Derek Jones8ede1a22011-10-05 13:34:52 -0500220
Derek Jonese69b4562011-10-05 17:30:50 -0500221.. note:: Please note that your _output() function will receive the data in its
222 finalized state. Benchmark and memory usage data will be rendered, cache
223 files written (if you have caching enabled), and headers will be sent
224 (if you use that :doc:`feature <../libraries/output>`) before it is
225 handed off to the _output() function.
226 To have your controller's output cached properly, its _output() method
227 can use::
Derek Jones8ede1a22011-10-05 13:34:52 -0500228
Derek Jonese69b4562011-10-05 17:30:50 -0500229 if ($this->output->cache_expiration > 0)
230 {
231 $this->output->_write_cache($output);
232 }
Derek Jones8ede1a22011-10-05 13:34:52 -0500233
Derek Jonese69b4562011-10-05 17:30:50 -0500234 If you are using this feature the page execution timer and memory usage
235 stats might not be perfectly accurate since they will not take into
236 acccount any further processing you do. For an alternate way to control
237 output *before* any of the final processing is done, please see the
238 available methods in the :doc:`Output Class <../libraries/output>`.
Derek Jones8ede1a22011-10-05 13:34:52 -0500239
240Private Functions
241=================
242
243In some cases you may want certain functions hidden from public access.
244To make a function private, simply add an underscore as the name prefix
245and it will not be served via a URL request. For example, if you were to
246have a function like this::
247
Derek Jonese69b4562011-10-05 17:30:50 -0500248 private function _utility()
249 {
250 // some code
251 }
Derek Jones8ede1a22011-10-05 13:34:52 -0500252
253Trying to access it via the URL, like this, will not work::
254
255 example.com/index.php/blog/_utility/
256
257Organizing Your Controllers into Sub-folders
258============================================
259
260If you are building a large application you might find it convenient to
261organize your controllers into sub-folders. CodeIgniter permits you to
262do this.
263
264Simply create folders within your application/controllers directory and
265place your controller classes within them.
266
267.. note:: When using this feature the first segment of your URI must
268 specify the folder. For example, lets say you have a controller located
269 here::
270
271 application/controllers/products/shoes.php
272
273 To call the above controller your URI will look something like this::
274
275 example.com/index.php/products/shoes/show/123
276
277Each of your sub-folders may contain a default controller which will be
278called if the URL contains only the sub-folder. Simply name your default
279controller as specified in your application/config/routes.php file
280
281CodeIgniter also permits you to remap your URIs using its :doc:`URI
282Routing <routing>` feature.
283
284Class Constructors
285==================
286
287If you intend to use a constructor in any of your Controllers, you
288**MUST** place the following line of code in it::
289
290 parent::__construct();
291
292The reason this line is necessary is because your local constructor will
293be overriding the one in the parent controller class so we need to
294manually call it.
295
296::
297
Derek Jonese69b4562011-10-05 17:30:50 -0500298 <?php
299 class Blog extends CI_Controller {
300
301 public function __construct()
302 {
303 parent::__construct();
304 // Your own constructor code
305 }
306 }
307 ?>
Derek Jones8ede1a22011-10-05 13:34:52 -0500308
309Constructors are useful if you need to set some default values, or run a
310default process when your class is instantiated. Constructors can't
311return a value, but they can do some default work.
312
313Reserved Function Names
314=======================
315
316Since your controller classes will extend the main application
317controller you must be careful not to name your functions identically to
318the ones used by that class, otherwise your local functions will
319override them. See :doc:`Reserved Names <reserved_names>` for a full
320list.
321
322That's it!
323==========
324
325That, in a nutshell, is all there is to know about controllers.