Readouble

Laravel 5.dev HTTPミドルウェア

イントロダクションIntroduction

HTTPミドルウェアはアプリケーションに入ってきたHTTPリクエストをフィルタリングする、便利なメカニズムを提供します。例えば、アプリケーションのユーザーが認証されているかを確認するミドルウェアが、Laravelには用意されています。ユーザーが認証されていなければ、このミドルウェアはユーザーをログインスクリーンへリダイレクトします。逆にそのユーザーが認証済みであれば、アプリケーションへリクエストされたURLへ進むことを許可します。HTTP middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

もちろん、認証の他にも多彩なタスクを実行するミドルウェアを書くことが可能です。CORSミドルウェアはアプリケーションから返されるレスポンス全部に、正しいヘッダーを追加することに責任を持つことでしょう。ログミドルウェアはアプリケーションにやってきたリクエスト全部をログすることに責任を負うことでしょう。Of course, middleware can be written to perform a variety of tasks besides authentication. A CORS middleware might be responsible for adding the proper headers to all responses leaving your application. A logging middleware might log all incoming requests to your application.

メンテナンスや認証、CSRF保護など、 Laravelには多くのミドルウェアが含まれています。これらのミドルウェアは全部、app/Http/Middlewareディレクトリーに設置されています。There are several middleware included in the Laravel framework, including middleware for maintenance, authentication, CSRF protection, and more. All of these middleware are located in the app/Http/Middleware directory.

ミドルウェア定義Defining Middleware

新しいミドルウェアを作成するには、make:middleware Artisanコマンドを使います。To create a new middleware, use the make:middleware Artisan command:

php artisan make:middleware OldMiddleware

このコマンドにより、OldMiddlewareクラスが、app/Http/Middlewareディレクトリー中に設置されます。このミドルウェアで、ageへ200歳以上が指定された場合のみ、アクセスを許してみましょう。そうでなければ、ユーザーを"home"のURIへリダイレクトし、戻します。This command will place a new OldMiddleware class within your app/Http/Middleware directory. In this middleware, we will only allow access to the route if the supplied age is greater than 200. Otherwise, we will redirect the users back to the "home" URI.

<?php namespace App\Http\Middleware;

class OldMiddleware {

	/**
	 * リクエストフィルターの実行
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @return mixed
	 */
	public function handle($request, Closure $next)
	{
		if ($request->input('age') < 200)
		{
			return redirect('home');
		}

		return $next($request);
	}

}

ご覧の通り、age200以下の場合、ミドルウェアはHTTPリダイレクトをクライアントへ返します。そうでなければ、リクエストはパスし、アプリケーションの先へ進めます。ミドルウェアのチェックに合格し、アプリケーションの先へリクエストを通すには、$requestを渡した$nextコールバックを呼び出すだけです。As you can see, if the given age is less than 200, the middleware will return an HTTP redirect to the client; otherwise, the request will be passed further into the application. To pass the request deeper into the application (allowing the middleware to "pass"), simply call the $next callback with the $request.

ミドルウェアを把握する一番よい方法は、HTTPリクエストがアプリケーションに届くまでに通過する、数々の「レイヤー(層)」だと考えてください。それぞれのレイヤーは、リクエストをテストし、完全に破棄することさえあるでしょう。It's best to envision middleware as a series of "layers" HTTP requests must pass through before they hit your application. Each layer can examine the request and even reject it entirely.

ミドルウェア登録Registering Middleware

グローバルミドルウェアGlobal Middleware

あるミドルウェアをアプリケーションの全HTTPリクエストで実行したい場合は、app/Http/Kernel.phpクラスの$middlewareプロパティへ追加してください。If you want a middleware to be run during every HTTP request to your application, simply list the middleware class in the $middleware property of your app/Http/Kernel.php class.

ミドルウェアのルートへの登録Assigning Middleware To Routes

特定のルートに対し、ミドルウェアを指定したい場合は、先ずapp/Http/Kernel.phpファイルでミドルウェアの短縮キーを登録します。デフォルト状態でこのクラスは、Laravelに含まれるミドルウェアのエントリーを$routeMiddlewareプロパティに含んでいます。自分のミドルウェアを追加するには、選んだキー名と共にリストへ付け加えるだけです。If you would like to assign middleware to specific routes, you should first assign the middleware a short-hand key in your app/Http/Kernel.php file. By default, the $routeMiddleware property of this class contains entries for the middleware included with Laravel. To add your own, simply append it to this list and assign it a key of your choosing.

HTTPカーネルへミドルウェアを定義し終えたら、そのmiddlewareキーをルートのオプション配列で指定できます。Once the middleware has been defined in the HTTP kernel, you may use the middleware key in the route options array:

Route::get('admin/profile', ['middleware' => 'auth', function()
{
	//
}]);

終了前ミドルウェアTerminable Middleware

時々、ミドルウェアはHTTPレスポンスがブラウザに送られた後に、何かの作業を行う必要があります。例えば、Laravelに含まれている「セッション」ミドルウェアは、ブラウザにレスポンスを送った、ストレージにセッションデーターを書き込こみます。これを行うには、"terminable"として、ミドルウェアを定義してください。Sometimes a middleware may need to do some work after the HTTP response has already been sent to the browser. For example, the "session" middleware included with Laravel writes the session data to storage after the response has been sent to the browser. To accomplish this, you may define the middleware as "terminable".

use Illuminate\Contracts\Routing\TerminableMiddleware;

class StartSession implements TerminableMiddleware {

	public function handle($request, $next)
	{
		return $next($request);
	}

	public function terminate($request, $response)
	{
		// Store the session data...
	}

}

ご覧の通り、handleメソッドの定義に加えて、TerminableMiddlewareterminateメソッドを定義しています。このメソッドは、リクエストとレスポンスの両方を受け取ります。terminableなミドルウェアを定義し終えたら、HTTPカーネルの中の、グローバルミドルウェアのリストに、付け加える必要があります。。As you can see, in addition to defining a handle method, TerminableMiddleware define a terminate method. This method receives both the request and the response. Once you have defined a terminable middleware, you should add it to the list of global middlewares in your HTTP kernel.

章選択

Artisan CLI

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作