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