PageRenderTime 43ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/en/core-libraries/components/request-handling.rst

https://gitlab.com/albertkeba/docs
ReStructuredText | 316 lines | 239 code | 77 blank | 0 comment | 0 complexity | 7a240a850869a4175007e6ab9528cb97 MD5 | raw file
  1. Request Handling
  2. ################
  3. .. php:class:: RequestHandlerComponent(ComponentCollection $collection, array $settings = array())
  4. The Request Handler component is used in CakePHP to obtain
  5. additional information about the HTTP requests that are made to
  6. your applications. You can use it to inform your controllers about
  7. AJAX as well as gain additional insight into content types that the
  8. client accepts and automatically changes to the appropriate layout
  9. when file extensions are enabled.
  10. By default RequestHandler will automatically detect AJAX requests
  11. based on the HTTP-X-Requested-With header that many javascript
  12. libraries use. When used in conjunction with
  13. :php:meth:`Router::parseExtensions()` RequestHandler will automatically switch
  14. the layout and view files to those that match the requested type.
  15. Furthermore, if a helper with the same name as the requested
  16. extension exists, it will be added to the Controllers Helper array.
  17. Lastly, if XML/JSON data is POST'ed to your Controllers, it will be
  18. parsed into an array which is assigned to ``$this->request->data``,
  19. and can then be saved as model data. In order to make use of
  20. RequestHandler it must be included in your $components array::
  21. class WidgetController extends AppController {
  22. public $components = array('RequestHandler');
  23. // Rest of controller
  24. }
  25. Obtaining Request Information
  26. =============================
  27. Request Handler has several methods that provide information about
  28. the client and its request.
  29. .. php:method:: accepts($type = null)
  30. $type can be a string, or an array, or null. If a string, accepts
  31. will return true if the client accepts the content type. If an
  32. array is specified, accepts return true if any one of the content
  33. types is accepted by the client. If null returns an array of the
  34. content-types that the client accepts. For example::
  35. class PostsController extends AppController {
  36. public $components = array('RequestHandler');
  37. public function beforeFilter() {
  38. if ($this->RequestHandler->accepts('html')) {
  39. // Execute code only if client accepts an HTML (text/html)
  40. // response
  41. } elseif ($this->RequestHandler->accepts('xml')) {
  42. // Execute XML-only code
  43. }
  44. if ($this->RequestHandler->accepts(array('xml', 'rss', 'atom'))) {
  45. // Executes if the client accepts any of the above: XML, RSS
  46. // or Atom
  47. }
  48. }
  49. }
  50. Other request 'type' detection methods include:
  51. .. php:method:: isXml()
  52. Returns true if the current request accepts XML as a response.
  53. .. php:method:: isRss()
  54. Returns true if the current request accepts RSS as a response.
  55. .. php:method:: isAtom()
  56. Returns true if the current call accepts an Atom response, false
  57. otherwise.
  58. .. php:method:: isMobile()
  59. Returns true if user agent string matches a mobile web browser, or
  60. if the client accepts WAP content. The supported Mobile User Agent
  61. strings are:
  62. - Android
  63. - AvantGo
  64. - BlackBerry
  65. - DoCoMo
  66. - Fennec
  67. - iPad
  68. - iPhone
  69. - iPod
  70. - J2ME
  71. - MIDP
  72. - NetFront
  73. - Nokia
  74. - Opera Mini
  75. - Opera Mobi
  76. - PalmOS
  77. - PalmSource
  78. - portalmmm
  79. - Plucker
  80. - ReqwirelessWeb
  81. - SonyEricsson
  82. - Symbian
  83. - UP.Browser
  84. - webOS
  85. - Windows CE
  86. - Windows Phone OS
  87. - Xiino
  88. .. php:method:: isWap()
  89. Returns true if the client accepts WAP content.
  90. All of the above request detection methods can be used in a similar
  91. fashion to filter functionality intended for specific content
  92. types. For example when responding to AJAX requests, you often will
  93. want to disable browser caching, and change the debug level.
  94. However, you want to allow caching for non-AJAX requests. The
  95. following would accomplish that::
  96. if ($this->request->is('ajax')) {
  97. $this->disableCache();
  98. }
  99. // Continue Controller action
  100. Obtaining Additional Client Information
  101. =======================================
  102. .. php:method:: getAjaxVersion()
  103. Gets Prototype version if call is AJAX, otherwise empty string. The
  104. Prototype library sets a special "Prototype version" HTTP header.
  105. Automatically decoding request data
  106. ===================================
  107. .. php:method:: addInputType($type, $handler)
  108. :param string $type: The content type alias this attached decoder is for.
  109. e.g. 'json' or 'xml'
  110. :param array $handler: The handler information for the type.
  111. Add a request data decoder. The handler should contain a callback, and any
  112. additional arguments for the callback. The callback should return
  113. an array of data contained in the request input. For example adding a CSV
  114. handler in your controllers' beforeFilter could look like::
  115. $parser = function ($data) {
  116. $rows = str_getcsv($data, "\n");
  117. foreach ($rows as &$row) {
  118. $row = str_getcsv($row, ',');
  119. }
  120. return $rows;
  121. };
  122. $this->RequestHandler->addInputType('csv', array($parser));
  123. The above example requires PHP 5.3, however you can use any
  124. `callable <http://php.net/callback>`_ for the handling function. You can
  125. also pass additional arguments to the callback, this is useful for callbacks
  126. like ``json_decode``::
  127. $this->RequestHandler->addInputType('json', array('json_decode', true));
  128. The above will make ``$this->request->data`` an array of the JSON input data,
  129. without the additional ``true`` you'd get a set of ``StdClass`` objects.
  130. Responding To Requests
  131. ======================
  132. In addition to request detection RequestHandler also provides easy
  133. access to altering the output and content type mappings for your
  134. application.
  135. .. php:method:: setContent($name, $type = null)
  136. :param string $name: The name or file extension of the Content-type
  137. ie. html, css, json, xml.
  138. :param mixed $type: The mime-type(s) that the Content-type maps to.
  139. setContent adds/sets the Content-types for the given name. Allows
  140. content-types to be mapped to friendly aliases and or extensions.
  141. This allows RequestHandler to automatically respond to requests of
  142. each type in its startup method. If you are using
  143. Router::parseExtension, you should use the file extension as the
  144. name of the Content-type. Furthermore, these content types are used
  145. by prefers() and accepts().
  146. setContent is best used in the beforeFilter() of your controllers,
  147. as this will best leverage the automagicness of content-type
  148. aliases.
  149. The default mappings are:
  150. - **javascript** text/javascript
  151. - **js** text/javascript
  152. - **json** application/json
  153. - **css** text/css
  154. - **html** text/html, \*/\*
  155. - **text** text/plain
  156. - **txt** text/plain
  157. - **csv** application/vnd.ms-excel, text/plain
  158. - **form** application/x-www-form-urlencoded
  159. - **file** multipart/form-data
  160. - **xhtml** application/xhtml+xml, application/xhtml, text/xhtml
  161. - **xhtml-mobile** application/vnd.wap.xhtml+xml
  162. - **xml** application/xml, text/xml
  163. - **rss** application/rss+xml
  164. - **atom** application/atom+xml
  165. - **amf** application/x-amf
  166. - **wap** text/vnd.wap.wml, text/vnd.wap.wmlscript,
  167. image/vnd.wap.wbmp
  168. - **wml** text/vnd.wap.wml
  169. - **wmlscript** text/vnd.wap.wmlscript
  170. - **wbmp** image/vnd.wap.wbmp
  171. - **pdf** application/pdf
  172. - **zip** application/x-zip
  173. - **tar** application/x-tar
  174. .. php:method:: prefers($type = null)
  175. Determines which content-types the client prefers. If no parameter
  176. is given the most likely content type is returned. If $type is an
  177. array the first type the client accepts will be returned.
  178. Preference is determined primarily by the file extension parsed by
  179. Router if one has been provided, and secondly by the list of
  180. content-types in HTTP\_ACCEPT.
  181. .. php:method:: renderAs($controller, $type)
  182. :param Controller $controller: Controller Reference
  183. :param string $type: friendly content type name to render content for ex.
  184. xml, rss.
  185. Change the render mode of a controller to the specified type. Will
  186. also append the appropriate helper to the controller's helper array
  187. if available and not already in the array.
  188. .. php:method:: respondAs($type, $options)
  189. :param string $type: Friendly content type name ex. xml, rss or a full
  190. content type like application/x-shockwave
  191. :param array $options: If $type is a friendly type name that has more than
  192. one content association, $index is used to select the content
  193. type.
  194. Sets the response header based on content-type map names.
  195. .. php:method:: responseType()
  196. Returns the current response type Content-type header or null if
  197. one has yet to be set.
  198. Taking advantage of HTTP cache validation
  199. =========================================
  200. .. versionadded:: 2.1
  201. The HTTP cache validation model is one of the processes used for cache
  202. gateways, also known as reverse proxies, to determine if they can serve a
  203. stored copy of a response to the client. Under this model, you mostly save
  204. bandwidth, but when used correctly you can also save some CPU processing,
  205. reducing this way response times.
  206. Enabling the RequestHandlerComponent in your controller automatically activates
  207. a check done before rendering the view. This check compares the response object
  208. against the original request to determine whether the response was not modified
  209. since the last time the client asked for it.
  210. If response is evaluated as not modified, then the view rendering process is
  211. stopped, saving processing time, saving bandwidth and no content is returned to
  212. the client. The response status code is then set to `304 Not Modified`.
  213. You can opt-out this automatic checking by setting the ``checkHttpCache``
  214. setting to false::
  215. public $components = array(
  216. 'RequestHandler' => array(
  217. 'checkHttpCache' => false
  218. ));
  219. Using custom ViewClasses
  220. ========================
  221. .. versionadded:: 2.3
  222. When using JsonView/XmlView you might want to override the default serialization
  223. with a custom View class, or add View classes for other types.
  224. You can map existing and new types to your custom classes.
  225. .. php:method:: viewClassMap($type, $viewClass)
  226. :param string|array $type: The type string or map array with format ``array('json' => 'MyJson')``
  227. :param string $viewClass: The viewClass to be used for the type without `View` appended
  228. You can also set this automatically by using the ``viewClassMap`` setting::
  229. public $components = array(
  230. 'RequestHandler' => array(
  231. 'viewClassMap' => array(
  232. 'json' => 'ApiKit.MyJson',
  233. 'xml' => 'ApiKit.MyXml',
  234. 'csv' => 'ApiKit.Csv'
  235. )
  236. ));
  237. .. meta::
  238. :title lang=en: Request Handling
  239. :keywords lang=en: handler component,javascript libraries,public components,null returns,model data,request data,content types,file extensions,ajax,meth,content type,array,conjunction,cakephp,insight,php