
Request & Response Objects¶
Response¶
- class ¶
is the default response class in CakePHP. It encapsulates a number of features and functionality for generating HTTP responses in your application. It also assists in testing, as it can be mocked/stubbed allowing you to inspect headers that will be sent. Like , consolidates a number of methods previously found on , and . The old methods are deprecated in favour of using .
provides an interface to wrap the common response-related tasks such as:
Sending headers for redirects.
Sending content type headers.
Sending any header.
Sending the response body.
Dealing with Content Types¶
- ($contentType = null)¶
You can control the Content-Type of your application’s responses with . If your application needs to deal with content types that are not built into Response, you can map them with as well:
Usually, you’ll want to map additional content types in your controller’s callback, so you can leverage the automatic view switching features of if you are using it.
Sending Files¶
- ($path, $options = [])¶
There are times when you want to send files as responses for your requests. You can accomplish that by using :
As shown in the above example, you must pass the file path to the method. CakePHP will send a proper content type header if it’s a known file type listed in Cake\Http\Response::$_mimeTypes. You can add new types prior to calling by using the method.
If you want, you can also force a file to be downloaded instead of displayed in the browser by specifying the options:
The supported options are:
- name
The name allows you to specify an alternate file name to be sent to the user.
- download
A boolean value indicating whether headers should be set to force download.
Sending a String as File¶
You can respond with a file that does not exist on the disk, such as a pdf or an ics generated on the fly from a string:
Callbacks can also return the body as a string:
Setting Headers¶
- ($header, $value)¶
Setting headers is done with the method. Like all of the PSR-7 interface methods, this method returns a new instance with the new header:
Headers are not sent when set. Instead, they are held until the response is emitted by .
You can now use the convenience method to directly set or get the redirect location header.
Setting the Body¶
- ($string)¶
To set a string as the response body, do the following:
New in version was added in
- ($body)¶
To set the response body, use the method, which is provided by the :
-
-