Ground Sunlight

Windowsで作る - PHPプログラミングの開発環境

ユーザ用ツール

サイト用ツール


サイドバー

メインメニュー

XAMPP アレンジ

IED

WSL2

道具箱

リポジトリ編

フレームワーク編

公開ソフトウェア

メタ
リンク


このページへのアクセス
今日: 9 / 昨日: 1
総計: 1861

slim:4:response

文書の過去の版を表示しています。


編集中

Slim4 レスポンス

Version 4.5.0

y2sunlight 2020-09-23

Slim に戻る

関連記事

本章は以下のサイトの The Response のセクションを翻訳し若干の補足を加えたのもです。


Slimアプリのルート(route)とミドルウェアには、クライアントに返される現在のHTTPレスポンスを表すPSR-7レスポンスオブジェクトが与えられます。レスポンスオブジェクトは、HTTPレスポンスステータス、ヘッダー、およびボディを検査および操作できる PSR-7 ResponseInterface を実装します。


Responseオブジェクトを取得する方法

PSR-7レスポンスオブジェクトは、次のようにルート(route)コールバックの2番目の引数としてSlimアプリケーションルートに注入されます。

<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
 
require __DIR__ . '/../vendor/autoload.php';
 
$app = AppFactory::create();
 
$app->get('/hello', function (ServerRequest $request, Response $response) {
    $response->getBody()->write('Hello World');
    return $response;
});
 
$app->run();


レスポンスステータス

すべてのHTTPレスポンスには、数値のステータスコードがあります。ステータスコード は、クライアントに返されるHTTPレスポンスのタイプを識別します。PSR-7レスポンスオブジェクトのデフォルトのステータスコードは 200 (OK) です。以下のように getStatusCode() メソッドを使用して、PSR-7 Responseオブジェクトのステータスコードを取得できます。

$status = $response->getStatusCode();

PSR-7レスポンスオブジェクトをコピーして、次のような新しいステータスコードを割り当てることができます:

$newResponse = $response->withStatus(302);


レスポンスヘッダー

全てのHTTPレスポンスにはヘッダーがあります。これらはHTTPレスポンスを説明するメタデータで、レスポンスのボディには表示されません。PSR-7 レスポンスオブジェクトは、そのヘッダーを検査および操作するためのいくつかのメソッドを提供します。

Get All Headers

PSR-7 レスポンスオブジェクトの getHeaders() メソッドを使用して、すべてのHTTPレスポンスヘッダーを連想配列としてフェッチできます。結果として得られる連想配列のキーはヘッダー名であり、その値自体がそれぞれのヘッダー名の文字列値の数値配列です。

$headers = $response->getHeaders();
foreach ($headers as $name => $values) {
    echo $name . ": " . implode(", ", $values);
}


Get One Header

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-7Responseオブジェクトの getHeader($ name) メソッドを使用して、単一のヘッダーの値を取得できます。 これにより、指定されたヘッダー名の値の配列が返されます。 1つのHTTPヘッダーに複数の値が含まれる場合があることに注意してください。

$headerValueArray = $response->getHeader('Vary');

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 Responseオブジェクトの getHeaderLine($ name) メソッドを使用して、特定のヘッダーのすべての値を含むコンマ区切りの文字列をフェッチすることもできます。 getHeader($ name) メソッドとは異なり、このメソッドはコンマで区切られた文字列を返します。

$headerValueString = $response->getHeaderLine('Vary');


Detect Header

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

PSR-7Responseオブジェクトの hasHeader($ name) メソッドを使用して、ヘッダーの存在をテストできます。

if ($response->hasHeader('Vary')) {
    // Do something
}


Set Header

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

PSR-7Responseオブジェクトの withHeader($ name、$ value) メソッドを使用してヘッダー値を設定できます。

$newResponse = $oldResponse->withHeader('Content-type', 'application/json');
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.
リマインダー
Responseオブジェクトは不変です。 このメソッドは、新しいヘッダー値を持つResponseオブジェクトのコピーを返します。 このメソッドは破壊的であり、同じヘッダー名にすでに関連付けられている既存のヘッダー値を置き換えます。


Append Header

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

PSR-7Responseオブジェクトの withAddedHeader($ name、$ value) メソッドを使用してヘッダー値を追加できます。

$newResponse = $oldResponse->withAddedHeader('Allow', 'PUT');
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.
リマインダー
withHeader()メソッドとは異なり、このメソッドは、同じヘッダー名にすでに存在する値のセットに新しい値を追加します。 Responseオブジェクトは不変です。 このメソッドは、ヘッダー値が追加されたResponseオブジェクトのコピーを返します。


Remove Header

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

Responseオブジェクトの withoutHeader($ name) メソッドを使用してヘッダーを削除できます。

$newResponse = $oldResponse->withoutHeader('Allow');
リマインダー
Responseオブジェクトは不変です。 このメソッドは、ヘッダー値が追加されたResponseオブジェクトのコピーを返します。


The Response Body

An HTTP response typically has a body.

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 Requestオブジェクトと同様に、PSR-7Responseオブジェクトは本体を「Psr \ Http \ Message \ StreamInterface」のインスタンスとして実装します。 PSR-7 Responseオブジェクトの「getBody()」メソッドを使用して、HTTP応答本体の「StreamInterface」インスタンスを取得できます。 getBody() メソッドは、発信HTTP応答の長さが不明であるか、使用可能なメモリに対して大きすぎる場合に適しています。

$body = $response->getBody();

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-7Responseオブジェクトに書き込む必要があります。 次のように、「write()」メソッドを使用して「StreamInterface」インスタンスにコンテンツを書き込むことができます。

$body = $response->getBody();
$body->write('Hello');

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.

PSR-7Responseオブジェクトの本体をまったく新しい「StreamInterface」インスタンスに置き換えることもできます。 これは、コンテンツをリモートの宛先(ファイルシステムやリモートAPIなど)からHTTP応答にパイプ処理する場合に特に便利です。 PSR-7Responseオブジェクトの本体をその withBody(StreamInterface $ body) メソッドに置き換えることができます。 その引数は、 Psr \ Http \ Message \ StreamInterface のインスタンスでなければなりません。

use GuzzleHttp\Psr7\LazyOpenStream;
 
$newStream = new LazyOpenStream('/path/to/file', 'r');
$newResponse = $oldResponse->withBody($newStream);
Reminder
The Response object is immutable. This method returns a copy of the Response object that contains the new body.
リマインダー
Responseオブジェクトは不変です。 このメソッドは、新しい本文を含むResponseオブジェクトのコピーを返します。


Returning JSON

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

最も単純な形式では、JSONデータはデフォルトの200HTTPステータスコードで返すことができます。

$data = array('name' => 'Bob', 'age' => 40);
$payload = json_encode($data);
 
$response->getBody()->write($payload);
return $response
          ->withHeader('Content-Type', 'application/json');

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

カスタムHTTPステータスコードを使用してJSONデータを返すこともできます。

$data = array('name' => 'Rob', 'age' => 40);
$payload = json_encode($data);
 
$response->getBody()->write($payload);
return $response
          ->withHeader('Content-Type', 'application/json')
          ->withStatus(201);
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.
リマインダー
Responseオブジェクトは不変です。 このメソッドは、新しいContent-Typeヘッダーを持つResponseオブジェクトのコピーを返します。 このメソッドは破壊的であり、既存のContent-Typeヘッダーを置き換えます。


Returning a Redirect

You can redirect the HTTP client by using the Location header.

Locationヘッダーを使用して、HTTPクライアントをリダイレクトできます。

return $response
  ->withHeader('Location', 'https://www.example.com')
  ->withStatus(302);


コメント

コメントを入力. Wiki文法が有効です:
 
slim/4/response.1601973487.txt.gz · 最終更新: 2020/10/06 17:38 by y2sunlight