Class RequestHandlerComponent

Request object for handling alternative HTTP requests

Alternative HTTP requests can come from wireless units like mobile phones, palmtop computers, and the like. These units have no use for Ajax requests, and this Component can tell how Cake should respond to the different needs of a handheld computer and a desktop machine.

CakeObject
Extended by Component
Extended by RequestHandlerComponent
Package: Cake\Controller\Component
Link: http://book.cakephp.org/2.0/en/core-libraries/components/request-handling.html
Copyright: Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
License: MIT License
Location: Cake/Controller/Component/RequestHandlerComponent.php

Properties summary

  • $_inputTypeMap protected
    array

    A mapping between extensions and deserializers for request bodies of that type. By default only JSON and XML are mapped, use RequestHandlerComponent::addInputType()

  • $_renderType protected
    string
    The template to use when rendering the given content type.
  • $_viewClassMap protected
    array

    A mapping between type and viewClass By default only JSON and XML are mapped, use RequestHandlerComponent::viewClassMap()

  • $ajaxLayout public
    string
    The layout that will be switched to for Ajax requests
  • $enabled public
    boolean
    Determines whether or not callbacks will be fired on this component
  • $ext public
    string
    Contains the file extension parsed out by the Router
  • $request public
    Holds the reference to Controller::$request
  • $response public
    Holds the reference to Controller::$response

Inherited Properties

Method Summary

  • __construct() public
    Constructor. Parses the accepted content types accepted by the client using HTTP_ACCEPT
  • _setExtension() protected

    Set the extension based on the accept headers. Compares the accepted types and configured extensions. If there is one common type, that is assigned as the ext/content type for the response. Type with the highest weight will be set. If the highest weight has more then one type matching the extensions, the order in which extensions are specified determines which type will be set.

  • accepts() public

    Determines which content types the client accepts. Acceptance is based on the file extension parsed by the Router (if present), and by the HTTP_ACCEPT header. Unlike CakeRequest::accepts() this method deals entirely with mapped content types.

  • Add a new mapped input type. Mapped input types are automatically converted by RequestHandlerComponent during the startup() callback.

  • Handles (fakes) redirects for Ajax requests using requestAction() Modifies the $_POST and $_SERVER['REQUEST_METHOD'] to simulate a new GET request.

  • Checks if the response can be considered different according to the request headers, and the caching response headers. If it was not modified, then the render process is skipped. And the client will get a blank response with a "304 Not Modified" header.

  • convertXml() public

    Helper method to parse xml input data, due to lack of anonymous functions this lives here.

  • Gets Prototype version if call is Ajax, otherwise empty string. The Prototype library sets a special "Prototype version" HTTP header.

  • getClientIP() public
    Gets remote client IP
  • getReferer() public
    Gets the server name from which this request was referred
  • initialize() public

    Checks to see if a file extension has been parsed by the Router, or if the HTTP_ACCEPT_TYPE has matches only one content type with the supported extensions. If there is only one matching type between the supported content types & extensions, and the requested mime-types, RequestHandler::$ext is set to that value.

  • isAjax() public
    Returns true if the current HTTP request is Ajax, false otherwise
  • isAtom() public
    Returns true if the current call accepts an Atom response, false otherwise
  • isDelete() public
    Returns true if the current call a DELETE request
  • isFlash() public
    Returns true if the current HTTP request is coming from a Flash-based client
  • isGet() public
    Returns true if the current call a GET request
  • isMobile() public

    Returns true if user agent string matches a mobile web browser, or if the client accepts WAP content.

  • isPost() public
    Returns true if the current call a POST request
  • isPut() public
    Returns true if the current call a PUT request
  • isRss() public
    Returns true if the current call accepts an RSS response, false otherwise
  • isSSL() public
    Returns true if the current request is over HTTPS, false otherwise.
  • isWap() public
    Returns true if the client accepts WAP content
  • isXml() public
    Returns true if the current call accepts an XML response, false otherwise
  • mapAlias() public
    Maps a content type alias back to its mime-type(s)
  • mapType() public
    Maps a content-type back to an alias
  • prefers() public

    Determines which content-types the client prefers. If no parameters are given, the single content-type that the client most likely prefers is returned. If $type is an array, the first item in the array that the client accepts is returned. Preference is determined primarily by the file extension parsed by the Router if provided, and secondarily by the list of content-types provided in HTTP_ACCEPT.

  • renderAs() public
    Sets the layout and template paths for the content type defined by $type.
  • Determines the content type of the data the client has sent (i.e. in a POST request)
  • respondAs() public

    Sets the response header based on type map index name. This wraps several methods available on CakeResponse. It also allows you to use Content-Type aliases.

  • Returns the current response type (Content-type header), or null if not alias exists
  • setContent() public

    Adds/sets the Content-type(s) for the given name. This method allows content-types to be mapped to friendly aliases (or extensions), which allows RequestHandler to automatically respond to requests of that type in the startup method.

  • startup() public

    The startup method of the RequestHandler enables several automatic behaviors related to the detection of certain properties of the HTTP request, including:

  • Getter/setter for viewClassMap

Method Detail

__construct()source public

__construct( ComponentCollection $collection , array $settings array() )

Constructor. Parses the accepted content types accepted by the client using HTTP_ACCEPT

Parameters

ComponentCollection $collection
ComponentCollection object.
array $settings optional array()
Array of settings.

Overrides

Component::__construct()

_setExtension()source protected

_setExtension( )

Set the extension based on the accept headers. Compares the accepted types and configured extensions. If there is one common type, that is assigned as the ext/content type for the response. Type with the highest weight will be set. If the highest weight has more then one type matching the extensions, the order in which extensions are specified determines which type will be set.

If html is one of the preferred types, no content type will be set, this is to avoid issues with browsers that prefer html and several other content types.

accepts()source public

accepts( string|array $type null )

Determines which content types the client accepts. Acceptance is based on the file extension parsed by the Router (if present), and by the HTTP_ACCEPT header. Unlike CakeRequest::accepts() this method deals entirely with mapped content types.

Usage:

$this->RequestHandler->accepts(array('xml', 'html', 'json'));

Returns true if the client accepts any of the supplied types.

$this->RequestHandler->accepts('xml');

Returns true if the client accepts xml.

Parameters

string|array $type optional null

Can be null (or no parameter), a string type name, or an array of types

Returns

mixed

If null or no parameter is passed, returns an array of content types the client accepts. If a string is passed, returns true if the client accepts it. If an array is passed, returns true if the client accepts one or more elements in the array.


See

RequestHandlerComponent::setContent()

addInputType()source public

addInputType( string $type , array $handler )

Add a new mapped input type. Mapped input types are automatically converted by RequestHandlerComponent during the startup() callback.

Parameters

string $type
The type alias being converted, ie. json
array $handler

The handler array for the type. The first index should be the handling callback, all other arguments should be additional parameters for the handler.

Throws

CakeException

beforeRedirect()source public

beforeRedirect( Controller $controller , string|array $url , integer|array $status null , boolean $exit true )

Handles (fakes) redirects for Ajax requests using requestAction() Modifies the $_POST and $_SERVER['REQUEST_METHOD'] to simulate a new GET request.

Parameters

Controller $controller
A reference to the controller
string|array $url
A string or array containing the redirect location
integer|array $status optional null
HTTP Status for redirect
boolean $exit optional true
Whether to exit script, defaults to true.

Overrides

Component::beforeRedirect()

beforeRender()source public

beforeRender( Controller $controller )

Checks if the response can be considered different according to the request headers, and the caching response headers. If it was not modified, then the render process is skipped. And the client will get a blank response with a "304 Not Modified" header.

Parameters

Controller $controller
Controller instance.

Returns

boolean
False if the render process should be aborted.

Overrides

Component::beforeRender()

convertXml()source public

convertXml( string $xml )

Helper method to parse xml input data, due to lack of anonymous functions this lives here.

Parameters

string $xml
XML string.

Returns

array
Xml array data

getAjaxVersion()source public

getAjaxVersion( )

Gets Prototype version if call is Ajax, otherwise empty string. The Prototype library sets a special "Prototype version" HTTP header.

Returns

string|boolean
When Ajax the prototype version of component making the call otherwise false

getClientIP()source public

getClientIP( boolean $safe true )

Gets remote client IP

Deprecated

3.0.0 Use $this->request->clientIp() from your, controller instead.

Parameters

boolean $safe optional true

Use safe = false when you think the user might manipulate their HTTP_CLIENT_IP header. Setting $safe = false will also look at HTTP_X_FORWARDED_FOR

Returns

string
Client IP address

getReferer()source public

getReferer( )

Gets the server name from which this request was referred

Deprecated

3.0.0 Use $this->request->referer() from your controller instead

Returns

string
Server address

initialize()source public

initialize( Controller $controller )

Checks to see if a file extension has been parsed by the Router, or if the HTTP_ACCEPT_TYPE has matches only one content type with the supported extensions. If there is only one matching type between the supported content types & extensions, and the requested mime-types, RequestHandler::$ext is set to that value.

Parameters

Controller $controller
A reference to the controller

See

Router::parseExtensions()

Overrides

Component::initialize()

isAjax()source public

isAjax( )

Returns true if the current HTTP request is Ajax, false otherwise

Deprecated

3.0.0 Use $this->request->is('ajax') instead.

Returns

boolean
True if call is Ajax

isAtom()source public

isAtom( )

Returns true if the current call accepts an Atom response, false otherwise

Returns

boolean
True if client accepts an RSS response

isDelete()source public

isDelete( )

Returns true if the current call a DELETE request

Deprecated

3.0.0 Use $this->request->is('delete'); from your controller.

Returns

boolean
True if call is a DELETE

isFlash()source public

isFlash( )

Returns true if the current HTTP request is coming from a Flash-based client

Deprecated

3.0.0 Use $this->request->is('flash') instead.

Returns

boolean
True if call is from Flash

isGet()source public

isGet( )

Returns true if the current call a GET request

Deprecated

3.0.0 Use $this->request->is('get'); from your controller.

Returns

boolean
True if call is a GET

isMobile()source public

isMobile( )

Returns true if user agent string matches a mobile web browser, or if the client accepts WAP content.

Returns

boolean
True if user agent is a mobile web browser

isPost()source public

isPost( )

Returns true if the current call a POST request

Deprecated

3.0.0 Use $this->request->is('post'); from your controller.

Returns

boolean
True if call is a POST

isPut()source public

isPut( )

Returns true if the current call a PUT request

Deprecated

3.0.0 Use $this->request->is('put'); from your controller.

Returns

boolean
True if call is a PUT

isRss()source public

isRss( )

Returns true if the current call accepts an RSS response, false otherwise

Returns

boolean
True if client accepts an RSS response

isSSL()source public

isSSL( )

Returns true if the current request is over HTTPS, false otherwise.

Deprecated

3.0.0 Use $this->request->is('ssl') instead.

Returns

boolean
True if call is over HTTPS

isWap()source public

isWap( )

Returns true if the client accepts WAP content

Returns

boolean

isXml()source public

isXml( )

Returns true if the current call accepts an XML response, false otherwise

Returns

boolean
True if client accepts an XML response

mapAlias()source public

mapAlias( string|array $alias )

Maps a content type alias back to its mime-type(s)

Parameters

string|array $alias
String alias to convert back into a content type. Or an array of aliases to map.

Returns

string|null

Null on an undefined alias. String value of the mapped alias type. If an alias maps to more than one content type, the first one will be returned.


mapType()source public

mapType( string|array $cType )

Maps a content-type back to an alias

Deprecated

3.0.0 Use $this->response->mapType() in your controller instead.

Parameters

string|array $cType
Either a string content type to map, or an array of types.

Returns

string|array
Aliases for the types provided.

prefers()source public

prefers( string|array $type null )

Determines which content-types the client prefers. If no parameters are given, the single content-type that the client most likely prefers is returned. If $type is an array, the first item in the array that the client accepts is returned. Preference is determined primarily by the file extension parsed by the Router if provided, and secondarily by the list of content-types provided in HTTP_ACCEPT.

Parameters

string|array $type optional null

An optional array of 'friendly' content-type names, i.e. 'html', 'xml', 'js', etc.

Returns

mixed

If $type is null or not provided, the first content-type in the list, based on preference, is returned. If a single type is provided a boolean will be returned if that type is preferred. If an array of types are provided then the first preferred type is returned. If no type is provided the first preferred type is returned.


See

RequestHandlerComponent::setContent()

renderAs()source public

renderAs( Controller $controller , string $type , array $options array() )

Sets the layout and template paths for the content type defined by $type.

Usage:

Render the response as an 'ajax' response.

$this->RequestHandler->renderAs($this, 'ajax');

Render the response as an xml file and force the result as a file download.

$this->RequestHandler->renderAs($this, 'xml', array('attachment' => 'myfile.xml');

Parameters

Controller $controller
A reference to a controller object
string $type
Type of response to send (e.g: 'ajax')
array $options optional array()
Array of options to use

See

RequestHandlerComponent::setContent()
RequestHandlerComponent::respondAs()

requestedWith()source public

requestedWith( string|array $type null )

Determines the content type of the data the client has sent (i.e. in a POST request)

Parameters

string|array $type optional null
Can be null (or no parameter), a string type name, or an array of types

Returns

mixed

If a single type is supplied a boolean will be returned. If no type is provided The mapped value of CONTENT_TYPE will be returned. If an array is supplied the first type in the request content type will be returned.


respondAs()source public

respondAs( string|array $type , array $options array() )

Sets the response header based on type map index name. This wraps several methods available on CakeResponse. It also allows you to use Content-Type aliases.

Parameters

string|array $type

Friendly type name, i.e. 'html' or 'xml', or a full content-type, like 'application/x-shockwave'.

array $options optional array()

If $type is a friendly type name that is associated with more than one type of content, $index is used to select which content-type to use.

Returns

boolean

Returns false if the friendly type name given in $type does not exist in the type map, or if the Content-type header has already been set by this method.


See

RequestHandlerComponent::setContent()

responseType()source public

responseType( )

Returns the current response type (Content-type header), or null if not alias exists

Returns

mixed

A string content type alias, or raw content type if no alias map exists, otherwise null


setContent()source public

setContent( string $name , string|array $type null )

Adds/sets the Content-type(s) for the given name. This method allows content-types to be mapped to friendly aliases (or extensions), which allows RequestHandler to automatically respond to requests of that type in the startup method.

Deprecated

3.0.0 Use $this->response->type() instead.

Parameters

string $name
The name of the Content-type, i.e. "html", "xml", "css"
string|array $type optional null

The Content-type or array of Content-types assigned to the name, i.e. "text/html", or "application/xml"

startup()source public

startup( Controller $controller )

The startup method of the RequestHandler enables several automatic behaviors related to the detection of certain properties of the HTTP request, including:

  • Disabling layout rendering for Ajax requests (based on the HTTP_X_REQUESTED_WITH header)
  • If Router::parseExtensions() is enabled, the layout and template type are switched based on the parsed extension or Accept-Type header. For example, if controller/action.xml is requested, the view path becomes app/View/Controller/xml/action.ctp. Also if controller/action is requested with Accept-Type: application/xml in the headers the view path will become app/View/Controller/xml/action.ctp. Layout and template types will only switch to mime-types recognized by CakeResponse. If you need to declare additional mime-types, you can do so using CakeResponse::type() in your controllers beforeFilter() method.
  • If a helper with the same name as the extension exists, it is added to the controller.
  • If the extension is of a type that RequestHandler understands, it will set that Content-type in the response header.
  • If the XML data is POSTed, the data is parsed into an XML object, which is assigned to the $data property of the controller, which can then be saved to a model object.

Parameters

Controller $controller
A reference to the controller

Overrides

Component::startup()

viewClassMap()source public

viewClassMap( array|string $type null , array $viewClass null )

Getter/setter for viewClassMap

Parameters

array|string $type optional null
The type string or array with format array('type' => 'viewClass') to map one or more
array $viewClass optional null
The viewClass to be used for the type without View appended

Returns

array|string
Returns viewClass when only string $type is set, else array with viewClassMap

Methods inherited from Component

__get()source public

__get( string $name )

Magic method for lazy loading $components.

Parameters

string $name
Name of component to get.

Returns

mixed
A Component object or null.

shutdown()source public

shutdown( Controller $controller )

Called after Controller::render() and before the output is printed to the browser.

Parameters

Controller $controller
Controller with components to shutdown

Link

http://book.cakephp.org/2.0/en/controllers/components.html#Component::shutdown

Methods inherited from CakeObject

_mergeVars()source protected

_mergeVars( array $properties , string $class , boolean $normalize true )

Merges this objects $property with the property in $class' definition. This classes value for the property will be merged on top of $class'

This provides some of the DRY magic CakePHP provides. If you want to shut it off, redefine this method as an empty function.

Parameters

array $properties
The name of the properties to merge.
string $class
The class to merge the property with.
boolean $normalize optional true
Set to true to run the properties through Hash::normalize() before merging.

_set()source protected

_set( array $properties array() )

Allows setting of multiple properties of the object in a single line of code. Will only set properties that are part of a class declaration.

Parameters

array $properties optional array()
An associative array containing properties and corresponding values.

_stop()source protected

_stop( integer|string $status 0 )

Stop execution of the current script. Wraps exit() making testing easier.

Parameters

integer|string $status optional 0
see http://php.net/exit for values

dispatchMethod()source public

dispatchMethod( string $method , array $params array() )

Calls a method on this object with the given parameters. Provides an OO wrapper for call_user_func_array

Parameters

string $method
Name of the method to call
array $params optional array()
Parameter list to use when calling $method

Returns

mixed
Returns the result of the method call

log()source public

log( string $msg , integer $type LOG_ERR , null|string|array $scope null )

Convenience method to write a message to CakeLog. See CakeLog::write() for more information on writing to logs.

Parameters

string $msg
Log message
integer $type optional LOG_ERR
Error type constant. Defined in app/Config/core.php.
null|string|array $scope optional null

The scope(s) a log message is being created in. See CakeLog::config() for more information on logging scopes.

Returns

boolean
Success of log write

requestAction()source public

requestAction( string|array $url , array $extra array() )

Calls a controller's method from any location. Can be used to connect controllers together or tie plugins into a main application. requestAction can be used to return rendered views or fetch the return value from controller actions.

Under the hood this method uses Router::reverse() to convert the $url parameter into a string URL. You should use URL formats that are compatible with Router::reverse()

Passing POST and GET data

POST and GET data can be simulated in requestAction. Use $extra['url'] for GET data. The $extra['data'] parameter allows POST data simulation.

Parameters

string|array $url

String or array-based URL. Unlike other URL arrays in CakePHP, this URL will not automatically handle passed and named arguments in the $url parameter.

array $extra optional array()

if array includes the key "return" it sets the AutoRender to true. Can also be used to submit GET/POST data, and named/passed arguments.

Returns

mixed

Boolean true or false on success/failure, or contents of rendered action if 'return' is set in $extra.


toString()source public

toString( )

CakeObject-to-string conversion. Each class can override this method as necessary.

Returns

string
The name of this class

Properties detail

$_inputTypeMapsource

protected array

A mapping between extensions and deserializers for request bodies of that type. By default only JSON and XML are mapped, use RequestHandlerComponent::addInputType()

array(
    'json' => array('json_decode', true)
)

$_renderTypesource

protected string

The template to use when rendering the given content type.

null

$_viewClassMapsource

protected array

A mapping between type and viewClass By default only JSON and XML are mapped, use RequestHandlerComponent::viewClassMap()

array(
    'json' => 'Json',
    'xml' => 'Xml'
)

$ajaxLayoutsource

public string

The layout that will be switched to for Ajax requests

See

RequestHandler::setAjax()
'ajax'

$enabledsource

public boolean

Determines whether or not callbacks will be fired on this component

true

$extsource

public string

Contains the file extension parsed out by the Router

See

Router::parseExtensions()
null

$requestsource

public CakeRequest

Holds the reference to Controller::$request

$responsesource

public CakeResponse

Holds the reference to Controller::$response

© 2005–2016 The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
https://api.cakephp.org/2.9/class-RequestHandlerComponent.html