Skip to content

Commit 6575fc4

Browse files
authored
Merge pull request #8228 from cakephp/5.x-request-response-cleanup
Improve request-response page
2 parents 419ce95 + 1a71ae9 commit 6575fc4

1 file changed

Lines changed: 58 additions & 67 deletions

File tree

docs/en/controllers/request-response.md

Lines changed: 58 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -67,9 +67,9 @@ well:
6767
$passedArgs = $this->request->getParam('pass');
6868
```
6969

70-
Will all provide you access to the passed arguments. There
71-
are several important/useful parameters that CakePHP uses internally, these
72-
are also all found in the routing parameters:
70+
This gives you access to passed arguments. There are several important
71+
parameters that CakePHP uses internally, and these are also all found in the
72+
routing parameters:
7373

7474
- `plugin` The plugin handling the request. Will be null when there is no
7575
plugin.
@@ -202,18 +202,18 @@ $error = $attachment->getError();
202202
```
203203

204204
Moving the uploaded file from its temporary location to the desired target
205-
location, doesn't require manually accessing the temporary file, instead it can
206-
be easily done by using the objects `moveTo()` method:
205+
location doesn't require manually accessing the temporary file. Instead, use the
206+
object's `moveTo()` method:
207207

208208
```php
209209
$attachment->moveTo($targetPath);
210210
```
211211

212-
In an HTTP environment, the `moveTo()` method will automatically validate
213-
whether the file is an actual uploaded file, and throw an exception in case
214-
necessary. In an CLI environment, where the concept of uploading files doesn't
215-
exist, it will allow to move the file that you've referenced irrespective of its
216-
origins, which makes testing file uploads possible.
212+
In an HTTP environment, the `moveTo()` method automatically validates
213+
whether the file is an actual uploaded file, and throws an exception when
214+
necessary. In a CLI environment, where the concept of uploading files doesn't
215+
exist, it allows moving the referenced file regardless of its origin, which
216+
makes testing file uploads possible.
217217

218218
`method` Cake\\Http\\ServerRequest::**getUploadedFile**(string $path): UploadedFileInterface|null
219219

@@ -276,7 +276,7 @@ $this->request = $this->request->withUploadedFiles($files);
276276
> request data (too), then you have to set them via `Cake\Http\ServerRequest::withData()` or
277277
> `Cake\Http\ServerRequest::withParsedBody()`.
278278
279-
### PUT, PATCH or DELETE Data
279+
### POST, PUT, PATCH, and DELETE
280280

281281
`method` Cake\\Http\\ServerRequest::**getBody**(): StreamInterface
282282

@@ -327,28 +327,32 @@ a setter for environment variables without having to modify globals
327327
$this->request->withEnv('REQUEST_METHOD', 'POST');
328328
```
329329

330-
### XML or JSON Data
330+
### Reading XML and JSON Payloads
331331

332332
Applications employing [REST](../development/rest) often exchange data in
333333
non-URL-encoded post bodies. You can read input data in any format using
334334
`Cake\Http\ServerRequest::input()`. By providing a decoding function,
335335
you can receive the content in a deserialized format:
336336

337-
```php
338-
// Get JSON encoded data submitted to a PUT/POST action
339-
$jsonData = $this->request->input('json_decode');
340-
```
341-
342337
Some deserializing methods require additional parameters when called, such as
343338
the 'as array' parameter on `json_decode`. If you want XML converted into a
344339
DOMDocument object, `Cake\Http\ServerRequest::input()` supports
345-
passing in additional parameters as well:
340+
passing additional parameters as well:
346341

347-
```php
348-
// Get XML encoded data submitted to a PUT/POST action
342+
::: code-group
343+
344+
```php [JSON]
345+
// Get JSON-encoded data submitted to a PUT/POST action
346+
$jsonData = $this->request->input('json_decode');
347+
```
348+
349+
```php [XML]
350+
// Get XML-encoded data submitted to a PUT/POST action
349351
$data = $this->request->input('Cake\Utility\Xml::build', ['return' => 'domdocument']);
350352
```
351353

354+
:::
355+
352356
### Path Information
353357

354358
The request object also provides useful information about the paths in your
@@ -371,7 +375,7 @@ $base = $request->getAttribute('webroot');
371375

372376
<a id="check-the-request"></a>
373377

374-
### Checking Request Conditions
378+
### Checking Request Conditions with `is()`
375379

376380
`method` Cake\\Http\\ServerRequest::**is**(array|string $type, mixed ...$args): bool
377381

@@ -535,7 +539,7 @@ Returns the HTTP method the request was made with:
535539
echo $request->getMethod();
536540
```
537541

538-
### Restricting Which HTTP method an Action Accepts
542+
### Restricting HTTP Methods per Action
539543

540544
`method` Cake\\Http\\ServerRequest::**allowMethod**(array|string $methods): bool
541545

@@ -547,7 +551,7 @@ Set allowed HTTP methods. If not matched, will throw
547551
public function delete()
548552
{
549553
// Only accept POST and DELETE requests
550-
$this->request->allowMethod(['post', 'delete']);
554+
$this->request->allowMethod(['post', 'delete']); // [!code focus]
551555
...
552556
}
553557
```
@@ -647,9 +651,7 @@ Check whether a specific language is accepted:
647651
$acceptsSpanish = $this->request->acceptLanguage('es-es');
648652
```
649653

650-
<a id="request-cookies"></a>
651-
652-
### Reading Cookies
654+
### Reading Request Cookies
653655

654656
Request cookies can be read through a number of methods:
655657

@@ -660,17 +662,17 @@ $rememberMe = $this->request->getCookie('remember_me');
660662
// Read the value, or get the default of 0
661663
$rememberMe = $this->request->getCookie('remember_me', 0);
662664

663-
// Get all cookies as an hash
665+
// Get all cookies as a hash
664666
$cookies = $this->request->getCookieParams();
665667

666668
// Get a CookieCollection instance
667669
$cookies = $this->request->getCookieCollection()
668670
```
669671

670672
See the `Cake\Http\Cookie\CookieCollection` documentation for how
671-
to work with cookie collection.
673+
to work with a cookie collection.
672674

673-
### Uploaded Files
675+
### Uploaded Files Quick Reference
674676

675677
Requests expose the uploaded file data in `getData()` or
676678
`getUploadedFiles()` as `UploadedFileInterface` objects:
@@ -682,13 +684,13 @@ $files = $request->getUploadedFiles();
682684
// Read the file data.
683685
$files[0]->getStream();
684686
$files[0]->getSize();
685-
$files[0]->getClientFileName();
687+
$files[0]->getClientFilename();
686688

687689
// Move the file.
688690
$files[0]->moveTo($targetPath);
689691
```
690692

691-
### Manipulating URIs
693+
### Working with the Request URI
692694

693695
Requests contain a URI object, which contains methods for interacting with the
694696
requested URI:
@@ -720,7 +722,7 @@ tasks such as:
720722
- Sending any header.
721723
- Sending the response body.
722724

723-
### Dealing with Content Types
725+
### Setting Content Types
724726

725727
`method` Cake\\Http\\Response::**withType**(string $contentType): static
726728

@@ -787,7 +789,7 @@ download
787789
A boolean value indicating whether headers should be set to force
788790
download.
789791

790-
### Sending a String as File
792+
### Sending a String as a File
791793

792794
You can respond with a file that does not exist on the disk, such as a pdf or an
793795
ics generated on the fly from a string:
@@ -943,9 +945,7 @@ The `withCache()` method sets the `Last-Modified` value to the first
943945
argument. `Expires` header and the `max-age` directive are set based on the
944946
second parameter. Cache-Control's `public` directive is set as well.
945947

946-
<a id="cake-response-caching"></a>
947-
948-
### Fine Tuning HTTP Cache
948+
### Fine-Tuning HTTP Cache
949949

950950
One of the best and easiest ways of speeding up your application is to use HTTP
951951
cache. Under this caching model, you are only required to help clients decide if
@@ -1118,8 +1118,6 @@ if ($this->response->isNotModified($this->request)) {
11181118
}
11191119
```
11201120

1121-
<a id="response-cookies"></a>
1122-
11231121
### Setting Cookies
11241122

11251123
Cookies can be added to response using either an array or a `Cake\Http\Cookie\Cookie`
@@ -1153,9 +1151,7 @@ will make the browser remove its local cookie:
11531151
$this->response = $this->response->withExpiredCookie(new Cookie('remember_me'));
11541152
```
11551153

1156-
<a id="cors-headers"></a>
1157-
1158-
### Setting Cross Origin Request Headers (CORS)
1154+
### Setting Cross-Origin Request Headers (CORS)
11591155

11601156
The `cors()` method returns a `CorsBuilder` instance which provides a fluent
11611157
interface for defining [HTTP Access Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS)
@@ -1184,19 +1180,15 @@ criteria are met:
11841180

11851181
The `CorsBuilder` provides the following methods for configuring CORS:
11861182

1187-
`method` Cake\\Http\\CorsBuilder::**allowOrigin**(array|string $domains): static
1188-
1189-
`method` Cake\\Http\\CorsBuilder::**allowMethods**(array $methods): static
1190-
1191-
`method` Cake\\Http\\CorsBuilder::**allowHeaders**(array $headers): static
1192-
1193-
`method` Cake\\Http\\CorsBuilder::**allowCredentials**(): static
1194-
1195-
`method` Cake\\Http\\CorsBuilder::**exposeHeaders**(array $headers): static
1196-
1197-
`method` Cake\\Http\\CorsBuilder::**maxAge**(string|int $age): static
1198-
1199-
`method` Cake\\Http\\CorsBuilder::**build**(): ResponseInterface
1183+
| Method | Signature |
1184+
| --- | --- |
1185+
| `allowOrigin` | `Cake\\Http\\CorsBuilder::allowOrigin(array\|string $domains): static` |
1186+
| `allowMethods` | `Cake\\Http\\CorsBuilder::allowMethods(array $methods): static` |
1187+
| `allowHeaders` | `Cake\\Http\\CorsBuilder::allowHeaders(array $headers): static` |
1188+
| `allowCredentials` | `Cake\\Http\\CorsBuilder::allowCredentials(): static` |
1189+
| `exposeHeaders` | `Cake\\Http\\CorsBuilder::exposeHeaders(array $headers): static` |
1190+
| `maxAge` | `Cake\\Http\\CorsBuilder::maxAge(string\|int $age): static` |
1191+
| `build` | `Cake\\Http\\CorsBuilder::build(): ResponseInterface` |
12001192

12011193
#### Practical CORS Examples
12021194

@@ -1310,16 +1302,16 @@ public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
13101302
}
13111303
```
13121304

1313-
### Running logic after the Response has been sent
1305+
### Running Logic After the Response Is Sent
13141306

1315-
In fastcgi based environments you can listen to the `Server.terminate` event
1307+
In FastCGI-based environments you can listen to the `Server.terminate` event
13161308
to run logic **after** the response has been sent to the client. The
13171309
`terminate` event will be passed a `request` and `response`. The
1318-
`request` is fetched from the applications' DI container, or from
1310+
`request` is fetched from the application's DI container, or from
13191311
`Router::getRequest()` if the DI container does not have a request registered.
13201312

13211313
> [!WARNING]
1322-
> In non fastcgi environments the `Server.terminate` event is fired before
1314+
> In non-FastCGI environments the `Server.terminate` event is fired before
13231315
> the response is sent.
13241316
13251317
::: info Added in version 5.1.0
@@ -1328,16 +1320,17 @@ to run logic **after** the response has been sent to the client. The
13281320
## Common Mistakes with Immutable Responses
13291321

13301322
Response objects offer a number of methods that treat
1331-
responses as immutable objects. Immutable objects help prevent difficult to
1332-
track accidental side-effects, and reduce mistakes caused by method calls caused
1333-
by refactoring that change ordering. While they offer a number of benefits,
1334-
immutable objects can take some getting used to. Any method that starts with
1323+
responses as immutable objects. Immutable objects help prevent difficult-to-
1324+
track accidental side effects, and reduce mistakes introduced during
1325+
refactoring. While they offer a number of benefits, immutable objects can take
1326+
some getting used to. Any method that starts with
13351327
`with` operates on the response in an immutable fashion, and will **always**
13361328
return a **new** instance. Forgetting to retain the modified instance is the most
13371329
frequent mistake people make when working with immutable objects:
13381330

13391331
```php
1340-
$this->response->withHeader('X-CakePHP', 'yes!');
1332+
$this->response->withHeader('X-CakePHP', 'yes!'); // [!code --]
1333+
$this->response = $this->response->withHeader('X-CakePHP', 'yes!'); // [!code ++]
13411334
```
13421335

13431336
In the above code, the response will be lacking the `X-CakePHP` header, as the
@@ -1420,9 +1413,7 @@ $response = $this->response->withCookieCollection($cookies);
14201413
Cookies set to responses can be encrypted using the
14211414
[Encrypted Cookie Middleware](../controllers/middleware#encrypted-cookie-middleware).
14221415

1423-
<a id="request-cookies"></a>
1424-
1425-
### Reading Cookies
1416+
### Reading Cookies from a CookieCollection
14261417

14271418
Once you have a `CookieCollection` instance, you can access the cookies it
14281419
contains:
@@ -1450,7 +1441,7 @@ collection if you modify a cookie:
14501441

14511442
```php
14521443
// Get the value
1453-
$value = $cookie->getValue()
1444+
$value = $cookie->getValue();
14541445

14551446
// Access data inside a JSON value
14561447
$id = $cookie->read('User.id');

0 commit comments

Comments
 (0)