0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめに

REST-API は PSR-7 準拠の Request/Response を採用しており、既存の PHP エコシステムと高い互換性を持ちます。
OAuth2 をはじめとした PSR-7 ベースの外部ライブラリとも自然に統合でき、既存アプリケーションとの連携も容易です。

本ページでは、REST-API が提供する PSR-7 ラッパーの仕様と、各イベント処理の引数として渡されるコンテキスト変数名を $ctx と仮定した場合の使用方法について詳しく解説します。

RequestWrapper

RequestWrapper は PSR-7 ServerRequestInterface をベースにした、 REST-API 専用のリクエスト操作クラスです。

HTTP メソッド、パス、クエリ、ボディ、ヘッダ、ファイルアップロード、 チャンク転送の受信など、REST-API で必要な情報へ簡潔にアクセスできます。

以下では 全メソッドの使用例 を掲載します。

method()

method() 使用例
$method = $ctx->request()->method();    // 'GET' など

HTTP メソッド(GET / POST など)を取得します。

path()

path() 使用例
$path = $ctx->request()->path();        // '/api/v1/users'

リクエストパス(パス部分のみ)を取得します。

query()

query() 使用例
$query = $ctx->request()->query();      // ['page' => 1, 'limit' => 20]

クエリパラメータを配列で取得します。

body()

body() 使用例
$body = $ctx->request()->body();        // JSON / XML / URL-encoded などのパース済みデータ

パーサーでパース済みのボディ部を取得します。
JSON / XML / URLエンコードは標準対応で、それ以外も設定ファイルで追加可能です。

cookies()

cookies() 使用例
$cookies = $ctx->request()->cookies();  // ['session_id' => 'xxxx']

Cookie 情報を配列で取得します。

files()

files() 使用例
$files = $ctx->request()->files();      // PSR-7 UploadedFileInterface[]

アップロードファイル情報を取得します。

header()

header() 使用例
$ua = $ctx->request()->header('User-Agent');

指定したヘッダを取得します。

params()

params() 使用例
$id = $ctx->request()->params('id');    // ルーティングの :id など
$all = $ctx->request()->params();       // 全パラメータ

ルーティングで設定した正規表現・名前付きパラメータを取得します。

stream()(チャンク転送受信 → StreamInterface 化)

stream() 使用例
$stream = $ctx->request()->stream();
$data = $stream->getContents();

チャンク転送などのストリーミングをストリーム形式で受信します。

raw()(チャンク転送受信・バイナリ)

raw() 使用例
$binary = $ctx->request()->raw();

チャンク転送系の受信データをバイナリ形式で扱います。

asFile()(チャンク転送 → UploadedFileInterface 化)

asFile() 使用例
$file = $ctx->request()->asFile();
$filename = $file->getClientFilename();

チャンク転送系の受信データをファイル形式で扱います。

getRequestInterface()

getRequestInterface() 使用例
$psr7 = $ctx->request()->getRequestInterface(); // OAuth2 ライブラリ等に渡す

PSR-7 の ServerRequestInterface をそのまま取得します。
OAuth2 ライブラリなど、PSR-7 対応ミドルウェアとの連携に利用できます。

ResponseWrapper

ResponseWrapper は REST-API のレスポンス送信を簡潔に行うためのクラスです。

text / json / file / download などの単発レスポンスに加え、 Chunked / SSE / Range といった高度なストリーミング送信にも対応しています。

status()

status() 使用例
$ctx->response()->status(404, 'Not Found');

ステータスコードを設定します。
第二パラメータは省略可能で、任意の理由句を設定できます。

getStatus()

getStatus() 使用例
$ctx->response()->getStatus();          // 200 など

現在のステータスコードを取得します。

getReason()

getReason() 使用例
$ctx->response()->getReason();          // 'Not Found' など

ステータスコードに対応する Reason-Phrase を取得します。

header()

header() 使用例
$ctx->response()->header('X-Sample', 'value');

レスポンスヘッダを設定します。

text()

text() 使用例
$ctx->response()->text('Hello');

プレーンテキストを送信します。

json()

json() 使用例
$ctx->response()->json(['message' => 'OK']);

JSON レスポンスを送信します。

file()

file() 使用例
$ctx->response()->file('./path/file.txt');

指定したファイルを送信します(静的ファイル向け)。

download()

download() 使用例
$ctx->response()->download('./path/file.txt', 'sample.txt');

Content-Disposition ヘッダを付与してダウンロード用として送信します。
第二パラメータには保存ダイアログで表示されるファイル名を指定します。

html() / javascript() / css()

html/js/css 使用例
$ctx->response()->html('./public/index.html');
$ctx->response()->javascript('./public/app.js');
$ctx->response()->css('./public/style.css');

HTML / JavaScript / CSS コンテンツを送信します。

chunked()(Chunked Transfer)

chunked() 使用例
$ctx->response()->chunked("分割データ");

Chunked Transfer による分割送信を行います。
end() を呼ぶ事でストリーミング送信を終了します。

event()(SSE:Server-Sent Events)

event() のパラメータは以下の 4 つです:

  • $p_data … data: に入る内容(必須)
  • $p_event … event: の値(任意)
  • $p_id … id: の値(任意)
  • $p_retry … retry: の値(任意)

PHP の 名前付き引数(Named Arguments) を使用する場合、 このフレームワークの命名規則により 必ず p_ で始まる名前 を指定してください。

1. 位置引数で全パラメータを指定する例

SSE 位置引数例
$ctx->response()->event(
    "メッセージ本文",
    "event-name",
    "event-id",
    5000
);

2. 名前付き引数で全パラメータを指定する例

SSE 名前付き引数例
$ctx->response()->event(
    p_data:  "メッセージ本文",
    p_event: "event-name",
    p_id:    "event-id",
    p_retry: 5000
);

3. 名前付き引数で必要な項目だけ指定する例

SSE 名前付き引数(省略)例
$ctx->response()->event(
    p_data: "メッセージ本文",
    p_id:   "event-id"
);

4. data のみを渡す最小例

SSE 最小例
$ctx->response()->event("メッセージ本文");

最後に end() を呼ぶ事でストリーミング送信を終了します。

end()(Chunked / SSE 終了)

end() 使用例
$ctx->response()->end();

ストリーミング送信を終了します。

rangeBinary()

rangeBinary() 使用例
$binary = file_get_contents('./movie.mp4');
$ctx->response()->rangeBinary($binary, 'video/mp4');

バイナリデータの全量を渡すだけで、Range 指定があればフレームワークが自動で切り出して返します。

rangeFile()

rangeFile() 使用例
$ctx->response()->rangeFile('./movie.mp4');

ファイルパスを渡すだけで、Range 指定に応じた部分送信をフレームワークが自動処理します。

sendResponseInterface()

sendResponseInterface() 使用例
$psr7 = $someLibrary->createResponse();
$ctx->response()->sendResponseInterface($psr7);

PSR-7 の ResponseInterface を送信します。
OAuth2 ライブラリなど、PSR-7 対応ミドルウェアとの連携に利用できます。

send()

send() 使用例
$ctx->response()->send();

準備されたレスポンスを最終的に送信します。
これを使ってボディ部がない場合に直ちに送信できます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?