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.php

Slim應用程序的路由和中間件被賦予一個PSR 7響應對象,該對象表示要返回給客戶機的當前HTTP響應。response對象實現了PSR 7 ResponseInterface,您可使用該接口檢查和操做HTTP響應狀態、報頭和正文。json

如何獲取響應對象

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應用程序路由中,以下所示:bash

<?php
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;

$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

<?php
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;

$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.ide

每一個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:fetch

您能夠複製一個PSR 7響應對象並分配一個新的狀態代碼,以下所示:ui

$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. Unlike the getHeader(name) method, this method returns a comma-separated string.

您還可使用PSR 7響應對象的getHeaderLine(name)方法獲取一個以逗號分隔的字符串,其中包含給定頭部的全部值。與getHeader(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(name,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(message,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(url,status = null) when you wish to return a redirect to another URL. You provide the url where you wish the client to be redirected to along with an optionalstatus code. The status code defaults to 302 if not provided.

當您但願返回到另外一個url的重定向時,Slim的響應對象有一個自定義方法withRedirect(url,status = null)。您提供一個但願客戶端被重定向到的url,以及一個可選的status代碼。若是沒有提供狀態碼,則默認爲302。

return $response->withRedirect('/new-url', 301);
複製代碼
相關文章
相關標籤/搜索