SlimPHP开发指南五:响应

概述

Your Slim app’s routes and middleware are given a PSR 7 response object that represents the current HTTP response to be returned to the client. The response object implements the PSR 7 ResponseInterface with which you can inspect and manipulate the HTTP response status, headers, and body.

Slim应用程序的路由和中间件被赋予一个PSR 7响应对象,该对象表示要返回给客户机的当前HTTP响应。response对象实现了PSR 7 ResponseInterface,您可以使用该接口检查和操作HTTP响应状态、报头和正文。

如何获取响应对象

The PSR 7 response object is injected into your Slim application routes as the second argument to the route callback like this:

将PSR 7响应对象作为路由回调的第二个参数注入到Slim应用程序路由中,如下所示:

$app = new \Slim\App;
$app->get('/foo', function (ServerRequestInterface $request, ResponseInterface $response) {
    // Use the PSR 7 $response object

    return $response;
});
$app->run();
复制代码
Figure 1: Inject PSR 7 response into application route callback.
复制代码

The PSR 7 response object is injected into your Slim application middleware as the second argument of the middleware callable like this:

PSR 7响应对象作为可调用的中间件的第二个参数注入到slim应用程序中间件中:

$app = new \Slim\App;
$app->add(function (ServerRequestInterface $request, ResponseInterface $response, callable $next) {
    // Use the PSR 7 $response object

    return $next($request, $response);
});
// Define app routes...
$app->run();
复制代码
Figure 2: Inject PSR 7 response into application middleware.
复制代码

相应状态

Every HTTP response has a numeric status code. The status code identifies the type of HTTP response to be returned to the client. The PSR 7 Response object’s default status code is 200 (OK). You can get the PSR 7 Response object’s status code with the getStatusCode() method like this.

每个HTTP响应都有一个数字状态码。状态代码标识要返回给客户机的HTTP响应的类型。PSR 7响应对象的默认状态代码是200 (OK)。可以使用getStatusCode()方法获得PSR 7响应对象的状态代码,如下所示。

$status = $response->getStatusCode();
复制代码
Figure 3: Get response status code.
复制代码

You can copy a PSR 7 Response object and assign a new status code like this:

您可以复制一个PSR 7响应对象并分配一个新的状态代码,如下所示:

$newResponse = $response->withStatus(302);
复制代码
Figure 4: Create response with new status code.
复制代码

响应头

Every HTTP response has headers. These are metadata that describe the HTTP response but are not visible in the response’s body. Slim’s PSR 7 Response object provides several methods to inspect and manipulate its headers.

每个HTTP响应都有头信息。这些元数据描述HTTP响应,但在响应主体中不可见。Slim的PSR 7响应对象提供了几种方法来检查和操作其头部。

得到所有头

You can fetch all HTTP response headers as an associative array with the PSR 7 Response object’s getHeaders() method. The resultant associative array’s keys are the header names and its values are themselves a numeric array of string values for their respective header name.

您可以使用PSR 7响应对象的getheader()方法以关联数组的形式获取所有HTTP响应头。由此产生的关联数组的键是标题名,其值本身是一个数字数组。

$headers = $response->getHeaders();
foreach ($headers as $name => $values) {
    echo $name . ": " . implode(", ", $values);
}
复制代码
Figure 5: Fetch and iterate all HTTP response headers as an associative array.
复制代码

得到一个头

You can get a single header’s value(s) with the PSR 7 Response object’s getHeader($name) method. This returns an array of values for the given header name. Remember, a single HTTP header may have more than one value!

您可以使用PSR 7响应对象的getHeader($name)方法获得单个报头的值。这将返回给定头名的值数组。记住,一个HTTP头可能有多个值!

$headerValueArray = $response->getHeader('Vary');
复制代码
Figure 6: Get values for a specific HTTP header.
复制代码

You may also fetch a comma-separated string with all values for a given header with the PSR 7 Response object’s getHeaderLine(name) method, this method returns a comma-separated string.

您还可以使用PSR 7响应对象的getHeaderLine(name)方法不同,该方法返回一个逗号分隔的字符串。

$headerValueString = $response->getHeaderLine('Vary');
复制代码
Figure 7: Get single header's values as comma-separated string.
复制代码

探测头

You can test for the presence of a header with the PSR 7 Response object’s hasHeader($name) method.

您可以使用PSR 7响应对象的hasHeader($name)方法测试报头是否存在。

if ($response->hasHeader('Vary')) {
    // Do something
}
复制代码
Figure 8: Detect presence of a specific HTTP header.
复制代码

Set Header

You can set a header value with the PSR 7 Response object’s withHeader(value) method.

$newResponse = $oldResponse->withHeader('Content-type', 'application/json');
复制代码
Figure 9: Set HTTP header
复制代码

Reminder 提醒:

The Response object is immutable. This method returns a copy of the Response object that has the new header value. This method is destructive, and it replaces existing header values already associated with the same header name.

响应对象是不可变的。此方法返回具有新头值的响应对象的副本。此方法是破坏性的,它替换已经与相同标题名称关联的现有标题值。

添加标题

You can append a header value with the PSR 7 Response object’s withAddedHeader($name, $value) method.

您可以使用PSR 7响应对象的withAddedHeader($name, $value)方法附加一个头值。

$newResponse = $oldResponse->withAddedHeader('Allow', 'PUT');
复制代码
Figure 10: Append HTTP header

Reminder
Unlike the withHeader() method, this method appends the new value to the set of values that already exist for the same header name. The Response object is immutable. This method returns a copy of the Response object that has the appended header value.
复制代码

移除头

You can remove a header with the Response object’s withoutHeader($name) method.

您可以使用响应对象的withoutHeader($name)方法删除标题。

$newResponse = $oldResponse->withoutHeader('Allow');
复制代码
Figure 11: Remove HTTP header
复制代码

Reminder 提醒:

The Response object is immutable. This method returns a copy of the Response object that has the appended header value.

响应对象是不可变的。此方法返回具有附加头值的响应对象的副本。

响应体

An HTTP response typically has a body. Slim provides a PSR 7 Response object with which you can inspect and manipulate the eventual HTTP response’s body.

HTTP响应通常有一个主体。Slim提供了一个PSR 7响应对象,您可以使用该对象检查和操作最终的HTTP响应主体。

Just like the PSR 7 Request object, the PSR 7 Response object implements the body as an instance of \Psr\Http\Message\StreamInterface. You can get the HTTP response body StreamInterface instance with the PSR 7 Response object’s getBody() method. The getBody() method is preferable if the outgoing HTTP response length is unknown or too large for available memory.

与PSR 7请求对象一样,PSR 7响应对象将主体实现为\ PSR \Http\Message\StreamInterface的一个实例。您可以使用PSR 7响应对象的getBody()方法获得HTTP响应体流接口实例。如果返回的HTTP响应长度未知或对于可用内存来说太长,则更适合用getBody()方法。

$body = $response->getBody();
复制代码
Figure 12: Get HTTP response body
复制代码

The resultant \Psr\Http\Message\StreamInterface instance provides the following methods to read from, iterate, and write to its underlying PHP resource.

生成的\Psr\Http\Message\StreamInterface实例提供了以下方法,可以从其中读取、迭代和写入底层PHP资源。

  • getSize()
  • tell()
  • eof()
  • isSeekable()
  • seek()
  • rewind()
  • isWritable()
  • write($string)
  • isReadable()
  • read($length)
  • getContents()
  • getMetadata($key = null)

Most often, you’ll need to write to the PSR 7 Response object. You can write content to the StreamInterface instance with its write() method like this:

最常见的情况是,您需要编写PSR 7响应对象。您可以使用它的write()方法将内容写入StreamInterface实例,如下所示:

$body = $response->getBody();
$body->write('Hello');
复制代码
Figure 13: Write content to the HTTP response body
复制代码

You can also replace the PSR 7 Response object’s body with an entirely new StreamInterface instance. This is particularly useful when you want to pipe content from a remote destination (e.g. the filesystem or a remote API) into the HTTP response. You can replace the PSR 7 Response object’s body with its withBody(StreamInterface $body) method. Its argument MUST be an instance of \Psr\Http\Message\StreamInterface.

您还可以使用一个全新的StreamInterface实例替换PSR 7响应对象的主体。当您希望将内容从远程目标(例如文件系统或远程API)导入HTTP响应时,这尤其有用。您可以用它的withBody(StreamInterface $body)方法替换PSR 7响应对象的主体。它的参数必须是\Psr\Http\Message\StreamInterface的一个实例。

\$newStream = new \GuzzleHttp\Psr7\LazyOpenStream('/path/to/file', 'r');
\$newResponse = $oldResponse->withBody(\$newStream);
复制代码
Figure 14: Replace the HTTP response body
复制代码

Reminder The Response object is immutable. This method returns a copy of the Response object that contains the new body.

返回JSON

Slim’s Response object has a custom method withJson($data, $status, $encodingOptions) to help simplify the process of returning JSON data.

Slim的响应对象有一个带有JSON ($data、$status、$encodingOptions)的自定义方法,以帮助简化返回JSON数据的过程。

The $data parameter contains the data structure you wish returned as JSON. $status is optional, and can be used to return a custom HTTP code. $encodingOptions is optional, and are the same encoding options used for json_encode().

$data参数包含您希望作为JSON返回的数据结构。$status是可选的,可用于返回自定义HTTP代码。$encodingOptions是可选的,与json_encode()使用的编码选项相同。

In it’s simplest form, JSON data can be returned with a default 200 HTTP status code.

在最简单的形式中,JSON数据可以使用默认的200 HTTP状态代码返回。

$data = array('name' => 'Bob', 'age' => 40);
$newResponse = $oldResponse->withJson($data);
复制代码
Figure 15: Returning JSON with a 200 HTTP status code.
复制代码

We can also return JSON data with a custom HTTP status code.

我们还可以使用定制的HTTP状态代码返回JSON数据。

$data = array('name' => 'Rob', 'age' => 40);
$newResponse = $oldResponse->withJson($data, 201);
复制代码
Figure 16: Returning JSON with a 201 HTTP status code.
复制代码

The Content-Type of the Response is automatically set to application/json;charset=utf-8.

响应的内容类型自动设置为application/json;charset=utf-8。

If there is a problem encoding the data to JSON, a \RuntimeException(code) is thrown containing the values of json_last_error_msg() as the $message and json_last_error() as the $code.

如果存在将数据编码为JSON的问题,将抛出一个\RuntimeException($message, $code),其中包含作为$message的json_last_error_msg()和作为$code的json_last_error()的值。

Reminder 提醒

The Response object is immutable. This method returns a copy of the Response object that has a new Content-Type header. This method is destructive, and it replaces the existing Content-Type header. The Status is also replaced if a $status was passed when withJson() was called.

返回一个重定向

Slim’s Response object has a custom method withRedirect(status = null) when you wish to return a redirect to another URL. You provide the status code. The status code defaults to 302 if not provided.

当您希望返回到另一个url的重定向时,Slim的响应对象有一个自定义方法withRedirect(status = null)。您提供一个希望客户端被重定向到的status代码。如果没有提供状态码,则默认为302。

return $response->withRedirect('/new-url', 301);
复制代码

转载于:https://juejin.im/post/5cb017bf5188251b2822c2e5

你可能感兴趣的:(SlimPHP开发指南五:响应)