RequestHandlerComponent
extends Component
in package
Request object handling for alternative HTTP requests.
See the 4.4 migration guide for how to upgrade. https://book.cakephp.org/4/en/appendices/4-4-migration-guide.html#requesthandlercomponent
This Component checks for requests for different content types like JSON, XML, XMLHttpRequest(AJAX) and configures the response object and view builder accordingly.
It can also check for HTTP caching headers like Last-Modified
, If-Modified-Since
etc. and return a response accordingly.
Tags
Table of Contents
Properties
- $_componentMap : array<string, array<string|int, mixed>>
- A component lookup table used to lazy load component objects.
- $_config : array<string, mixed>
- Runtime config
- $_configInitialized : bool
- Whether the config property has already been configured with defaults
- $_defaultConfig : array<string, mixed>
- Default config
- $_registry : ComponentRegistry
- Component registry class used to lazy load components.
- $_renderType : string|null
- The template type to use when rendering the given content type.
- $components : array<string|int, mixed>
- Other Components this component uses.
- $ext : string|null
- Contains the file extension parsed out by the Router
Methods
- __construct() : mixed
- Constructor. Parses the accepted content types accepted by the client using HTTP_ACCEPT
- __debugInfo() : array<string, mixed>
- Returns an array that can be used to describe the internal state of this object.
- __get() : Component|null
- Magic method for lazy loading $components.
- accepts() : array<string|int, mixed>|bool|string|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 {@link \Cake\Http\ServerRequest::accepts()} this method deals entirely with mapped content types.
- beforeRender() : void
- 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.
- configShallow() : $this
- Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
- getConfig() : mixed
- Returns the config.
- getConfigOrFail() : mixed
- Returns the config for this specific key.
- getController() : Controller
- Get the controller this component is bound to.
- implementedEvents() : array<string, mixed>
- Events supported by this component.
- initialize() : void
- Constructor hook method.
- log() : bool
- Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
- mapAlias() : array<string|int, mixed>|string|null
- Maps a content type alias back to its mime-type(s)
- prefers() : string|bool|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.
- renderAs() : void
- Sets either the view class if one exists or the layout and template path of the view.
- requestedWith() : mixed
- Determines the content type of the data the client has sent (i.e. in a POST request)
- respondAs() : bool
- Sets the response header based on type map index name. This wraps several methods available on {@link \Cake\Http\Response}. It also allows you to use Content-Type aliases.
- setConfig() : $this
- Sets the config.
- startup() : void
- The startup method of the RequestHandler enables several automatic behaviors related to the detection of certain properties of the HTTP request, including:
- _configDelete() : void
- Deletes a single config key.
- _configRead() : mixed
- Reads a config key.
- _configWrite() : void
- Writes a config key.
- _setExtension() : void
- Set the extension based on the `Accept` header or URL extension.
Properties
$_componentMap
A component lookup table used to lazy load component objects.
protected
array<string, array<string|int, mixed>>
$_componentMap
= []
$_config
Runtime config
protected
array<string, mixed>
$_config
= []
$_configInitialized
Whether the config property has already been configured with defaults
protected
bool
$_configInitialized
= false
$_defaultConfig
Default config
protected
array<string, mixed>
$_defaultConfig
= ['checkHttpCache' => true, 'viewClassMap' => []]
These are merged with user-provided config when the component is used.
-
checkHttpCache
- Whether to check for HTTP cache. Defaulttrue
. -
viewClassMap
- Mapping between type and view classes. If undefined JSON, XML, and AJAX will be mapped. Defining any types will omit the defaults.
$_registry
Component registry class used to lazy load components.
protected
ComponentRegistry
$_registry
$_renderType
The template type to use when rendering the given content type.
protected
string|null
$_renderType
$components
Other Components this component uses.
protected
array<string|int, mixed>
$components
= []
$ext
Contains the file extension parsed out by the Router
protected
string|null
$ext
Tags
Methods
__construct()
Constructor. Parses the accepted content types accepted by the client using HTTP_ACCEPT
public
__construct(ComponentRegistry $registry[, array<string, mixed> $config = [] ]) : mixed
Parameters
- $registry : ComponentRegistry
-
ComponentRegistry object.
- $config : array<string, mixed> = []
-
Array of config.
__debugInfo()
Returns an array that can be used to describe the internal state of this object.
public
__debugInfo() : array<string, mixed>
Return values
array<string, mixed>__get()
Magic method for lazy loading $components.
public
__get(string $name) : Component|null
Parameters
- $name : string
-
Name of component to get.
Return values
Component|null —A Component object or null.
accepts()
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 {@link \Cake\Http\ServerRequest::accepts()} this method deals entirely with mapped content types.
public
accepts([array<string|int, string>|string|null $type = null ]) : array<string|int, mixed>|bool|string|null
Use ContentTypeNegotiation::prefersChoice() or Controller::getViewClasses() instead.
Usage:
$this->RequestHandler->accepts(['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
- $type : array<string|int, string>|string|null = null
-
Can be null (or no parameter), a string type name, or an array of types
Return values
array<string|int, mixed>|bool|string|null —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.
beforeRender()
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.
public
beforeRender(EventInterface $event) : void
- If Router::extensions() is enabled, the layout and template type are
switched based on the parsed extension or
Accept
header. For example, ifcontroller/action.xml
is requested, the view path becomestemplates/Controller/xml/action.php
. Also, ifcontroller/action
is requested withAccept: application/xml
in the headers the view path will becometemplates/Controller/xml/action.php
. Layout and template types will only switch to mime-types recognized by \Cake\Http\Response. If you need to declare additional mime-types, you can do so using in your controller's 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.
Parameters
- $event : EventInterface
-
The Controller.beforeRender event.
Tags
configShallow()
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
public
configShallow(array<string, mixed>|string $key[, mixed|null $value = null ]) : $this
Setting a specific value:
$this->configShallow('key', $value);
Setting a nested value:
$this->configShallow('some.nested.key', $value);
Updating multiple config settings at the same time:
$this->configShallow(['one' => 'value', 'another' => 'value']);
Parameters
- $key : array<string, mixed>|string
-
The key to set, or a complete array of configs.
- $value : mixed|null = null
-
The value to set.
Return values
$thisgetConfig()
Returns the config.
public
getConfig([string|null $key = null ][, mixed $default = null ]) : mixed
Usage
Reading the whole config:
$this->getConfig();
Reading a specific value:
$this->getConfig('key');
Reading a nested value:
$this->getConfig('some.nested.key');
Reading with default value:
$this->getConfig('some-key', 'default-value');
Parameters
- $key : string|null = null
-
The key to get or null for the whole config.
- $default : mixed = null
-
The return value when the key does not exist.
Return values
mixed —Configuration data at the named key or null if the key does not exist.
getConfigOrFail()
Returns the config for this specific key.
public
getConfigOrFail(string $key) : mixed
The config value for this key must exist, it can never be null.
Parameters
- $key : string
-
The key to get.
Tags
Return values
mixed —Configuration data at the named key
getController()
Get the controller this component is bound to.
public
getController() : Controller
Return values
Controller —The bound controller.
implementedEvents()
Events supported by this component.
public
implementedEvents() : array<string, mixed>
Return values
array<string, mixed>initialize()
Constructor hook method.
public
initialize(array<string, mixed> $config) : void
Implement this method to avoid having to overwrite the constructor and call parent.
Parameters
- $config : array<string, mixed>
-
The configuration settings provided to this component.
log()
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
public
log(string $message[, string|int $level = LogLevel::ERROR ][, array<string|int, mixed>|string $context = [] ]) : bool
Parameters
- $message : string
-
Log message.
- $level : string|int = LogLevel::ERROR
-
Error level.
- $context : array<string|int, mixed>|string = []
-
Additional log data relevant to this message.
Return values
bool —Success of log write.
mapAlias()
Maps a content type alias back to its mime-type(s)
public
mapAlias(array<string|int, mixed>|string $alias) : array<string|int, mixed>|string|null
Parameters
- $alias : array<string|int, mixed>|string
-
String alias to convert back into a content type. Or an array of aliases to map.
Return values
array<string|int, mixed>|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. If an array is provided for $alias, an array of mapped types will be returned.
prefers()
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.
public
prefers([array<string|int, string>|string|null $type = null ]) : string|bool|null
Use Controller::getViewClasses() instead.
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
- $type : array<string|int, string>|string|null = null
-
An optional array of 'friendly' content-type names, i.e. 'html', 'xml', 'js', etc.
Return values
string|bool|null —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.
renderAs()
Sets either the view class if one exists or the layout and template path of the view.
public
renderAs(Controller $controller, string $type[, array<string, mixed> $options = [] ]) : void
The names of these are derived from the $type input parameter.
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', ['attachment' => 'myfile.xml'];
Parameters
- $controller : Controller
-
A reference to a controller object
- $type : string
-
Type of response to send (e.g: 'ajax')
- $options : array<string, mixed> = []
-
Array of options to use
Tags
requestedWith()
Determines the content type of the data the client has sent (i.e. in a POST request)
public
requestedWith([array<string|int, string>|string|null $type = null ]) : mixed
Parameters
- $type : array<string|int, string>|string|null = null
-
Can be null (or no parameter), a string type name, or an array of types
Return values
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()
Sets the response header based on type map index name. This wraps several methods available on {@link \Cake\Http\Response}. It also allows you to use Content-Type aliases.
public
respondAs(string $type[, array<string, mixed> $options = [] ]) : bool
Parameters
- $type : string
-
Friendly type name, i.e. 'html' or 'xml', or a full content-type, like 'application/x-shockwave'.
- $options : array<string, mixed> = []
-
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.
Return values
bool —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.
setConfig()
Sets the config.
public
setConfig(array<string, mixed>|string $key[, mixed|null $value = null ][, bool $merge = true ]) : $this
Usage
Setting a specific value:
$this->setConfig('key', $value);
Setting a nested value:
$this->setConfig('some.nested.key', $value);
Updating multiple config settings at the same time:
$this->setConfig(['one' => 'value', 'another' => 'value']);
Parameters
- $key : array<string, mixed>|string
-
The key to set, or a complete array of configs.
- $value : mixed|null = null
-
The value to set.
- $merge : bool = true
-
Whether to recursively merge or overwrite existing config, defaults to true.
Tags
Return values
$thisstartup()
The startup method of the RequestHandler enables several automatic behaviors related to the detection of certain properties of the HTTP request, including:
public
startup(EventInterface $event) : void
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
- $event : EventInterface
-
The startup event that was fired.
_configDelete()
Deletes a single config key.
protected
_configDelete(string $key) : void
Parameters
- $key : string
-
Key to delete.
Tags
_configRead()
Reads a config key.
protected
_configRead(string|null $key) : mixed
Parameters
- $key : string|null
-
Key to read.
_configWrite()
Writes a config key.
protected
_configWrite(array<string, mixed>|string $key, mixed $value[, string|bool $merge = false ]) : void
Parameters
- $key : array<string, mixed>|string
-
Key to write to.
- $value : mixed
-
Value to write.
- $merge : string|bool = false
-
True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
Tags
_setExtension()
Set the extension based on the `Accept` header or URL extension.
protected
_setExtension(ServerRequest $request, Response $response) : void
Compares the accepted types and configured extensions. If there is one common type, that is assigned as the ext/content type for the response. The type with the highest weight will be set. If the highest weight has more than 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.
Parameters
- $request : ServerRequest
-
The request instance.
- $response : Response
-
The response instance.