PageRenderTime 47ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/user_guide_src/source/general/controllers.rst

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