blob: 6e50794191bce64f3dcfffb70d96f19fbf597c30 [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
purwandi02df61f2011-10-07 15:33:40 +070013**A Controller is simply a class file that is named in a way that can be
14associated with a URI.**
Derek Jones8ede1a22011-10-05 13:34:52 -050015
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.
purwandi02df61f2011-10-07 15:33:40 +0700139To specify a default controller, open your **application/config/routes.php**
Derek Jones8ede1a22011-10-05 13:34:52 -0500140file 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
purwandi02df61f2011-10-07 15:33:40 +0700202can be found in the :doc:`Views <views>` and :doc:`Output class <../libraries/output>` pages. In some cases, however, you
Derek Jones8ede1a22011-10-05 13:34:52 -0500203might want to post-process the finalized data in some way and send it to
204the browser yourself. CodeIgniter permits you to add a function named
205_output() to your controller that will receive the finalized output
206data.
207
208.. important:: If your controller contains a function named _output(),
209 it will **always** be called by the output class instead of echoing the
210 finalized data directly. The first parameter of the function will
211 contain the finalized output.
212
213Here is an example::
214
Derek Jonese69b4562011-10-05 17:30:50 -0500215 public function _output($output)
216 {
217 echo $output;
218 }
Derek Jones8ede1a22011-10-05 13:34:52 -0500219
Derek Jonese69b4562011-10-05 17:30:50 -0500220.. note:: Please note that your _output() function will receive the data in its
221 finalized state. Benchmark and memory usage data will be rendered, cache
222 files written (if you have caching enabled), and headers will be sent
223 (if you use that :doc:`feature <../libraries/output>`) before it is
224 handed off to the _output() function.
225 To have your controller's output cached properly, its _output() method
226 can use::
Derek Jones8ede1a22011-10-05 13:34:52 -0500227
Derek Jonese69b4562011-10-05 17:30:50 -0500228 if ($this->output->cache_expiration > 0)
229 {
230 $this->output->_write_cache($output);
231 }
Derek Jones8ede1a22011-10-05 13:34:52 -0500232
Derek Jonese69b4562011-10-05 17:30:50 -0500233 If you are using this feature the page execution timer and memory usage
234 stats might not be perfectly accurate since they will not take into
235 acccount any further processing you do. For an alternate way to control
236 output *before* any of the final processing is done, please see the
237 available methods in the :doc:`Output Class <../libraries/output>`.
Derek Jones8ede1a22011-10-05 13:34:52 -0500238
239Private Functions
240=================
241
242In some cases you may want certain functions hidden from public access.
243To make a function private, simply add an underscore as the name prefix
244and it will not be served via a URL request. For example, if you were to
245have a function like this::
246
Derek Jonese69b4562011-10-05 17:30:50 -0500247 private function _utility()
248 {
249 // some code
250 }
Derek Jones8ede1a22011-10-05 13:34:52 -0500251
252Trying to access it via the URL, like this, will not work::
253
254 example.com/index.php/blog/_utility/
255
256Organizing Your Controllers into Sub-folders
257============================================
258
259If you are building a large application you might find it convenient to
260organize your controllers into sub-folders. CodeIgniter permits you to
261do this.
262
263Simply create folders within your application/controllers directory and
264place your controller classes within them.
265
266.. note:: When using this feature the first segment of your URI must
267 specify the folder. For example, lets say you have a controller located
268 here::
269
270 application/controllers/products/shoes.php
271
272 To call the above controller your URI will look something like this::
273
274 example.com/index.php/products/shoes/show/123
275
276Each of your sub-folders may contain a default controller which will be
277called if the URL contains only the sub-folder. Simply name your default
278controller as specified in your application/config/routes.php file
279
280CodeIgniter also permits you to remap your URIs using its :doc:`URI
281Routing <routing>` feature.
282
283Class Constructors
284==================
285
286If you intend to use a constructor in any of your Controllers, you
287**MUST** place the following line of code in it::
288
289 parent::__construct();
290
291The reason this line is necessary is because your local constructor will
292be overriding the one in the parent controller class so we need to
293manually call it.
294
295::
296
Derek Jonese69b4562011-10-05 17:30:50 -0500297 <?php
298 class Blog extends CI_Controller {
299
300 public function __construct()
301 {
302 parent::__construct();
303 // Your own constructor code
304 }
305 }
306 ?>
Derek Jones8ede1a22011-10-05 13:34:52 -0500307
308Constructors are useful if you need to set some default values, or run a
309default process when your class is instantiated. Constructors can't
310return a value, but they can do some default work.
311
312Reserved Function Names
313=======================
314
315Since your controller classes will extend the main application
316controller you must be careful not to name your functions identically to
317the ones used by that class, otherwise your local functions will
318override them. See :doc:`Reserved Names <reserved_names>` for a full
319list.
320
321That's it!
322==========
323
324That, in a nutshell, is all there is to know about controllers.