ホームページ  >  記事  >  バックエンド開発  >  laravel5.2-httpミドルウェア学習

laravel5.2-httpミドルウェア学習

WBOY
WBOYオリジナル
2016-06-20 12:34:571212ブラウズ

HTTP ミドルウェア

はじめに

HTTP ミドルウェアは、アプリケーションに入る HTTP リクエストをフィルタリングするための便利なメカニズムを提供します。たとえば、Laravel には、アプリケーションのユーザーが認証されていることを確認するミドルウェアが含まれています。ユーザーが認証されていない場合、ミドルウェアはユーザーをログイン画面にリダイレクトします。ただし、ユーザーが認証されている場合、ミドルウェアはリクエストがアプリケーションにさらに進むことを許可します。

もちろん、認証以外のさまざまなタスクを実行する追加のミドルウェアを作成することもできます。 CORS ミドルウェアは、アプリケーションから送信されるすべての応答に適切なヘッダーを追加する役割を担う場合があります。ロギングミドルウェアは、アプリケーションに受信するすべてのリクエストを記録する場合があります。

Laravel フレームワークには、メンテナンス、認証、CSRF 保護などのためのミドルウェアを含む、いくつかのミドルウェアが含まれています。これらのミドルウェアはすべて app/Http/Middleware ディレクトリにあります。

ミドルウェアの定義

新しいミドルウェアを作成するには、make:middlewareArtisan コマンドを使用します。

创建中间件可使用工具创建、artisan 是个帮助你创建一部的中间件或者他の好ツール、

php artisan make:middleware AgeMiddleware

このコマンドは、アプリ/HTTP/ミドルウェアの目录里面にある中間コンポーネント (これはクラス) を作成しており、文書の里面にはいくつかの優れたモジュールが含まれています。例这里,

cat app/Http/Middleware/AgeMiddleware.php< ?phpnamespace App\Http\Middleware;use Closure;class AgeMiddleware{    /**     * Handle an incoming request.     *     * @param  \Illuminate\Http\Request  $request     * @param  \Closure  $next     * @return mixed     */    public function handle($request, Closure $next)//支持2个参数,一个是request,另外是一个闭包(暂时未知)    {        return $next($request); //返回一个处理过的$request    }}//这个只是默认样例。

このコマンドは、app/Http/Middleware ディレクトリ内に新しい AgeMiddlewareclass を配置します。このミドルウェアでは、指定された age が 200 を超える場合にのみルートへのアクセスを許可します。それ以外の場合は、ユーザーを「ホーム」URI にリダイレクトします。

この中間ファイルは修正されており、サポート年齢が 200 を超える请要求を変更するだけです

<?phpnamespace App\Http\Middleware;use Closure;class AgeMiddleware{    /**     * Run the request filter.     *     * @param  \Illuminate\Http\Request  $request     * @param  \Closure  $next     * @return mixed     */    public function handle($request, Closure $next)    {        if ($request->input('age') < = 200) {//调用input方法,并且传入参数age,            return redirect('home');        }        return $next($request);    }}

ご覧のとおり、指定された年齢が 200 以下の場合、ミドルウェアはクライアントに HTTP リダイレクトを返します。それ以外の場合、リクエストはさらにアプリケーションに渡されます。リクエストをアプリケーションのさらに奥深くに渡すには (ミドルウェアが「渡す」ことを許可します)、$request を指定して $nextcallback を呼び出すだけです。

ミドルウェアには点像フィルターがあり、一連のフィルター層が不断に通過http请求をイメージします。リクエストはアプリケーションに到達する前に通過する必要があります。各層はリクエストを検査し、リクエストを完全に拒否することもできます。

Before/AfterMiddleware

ミドルウェアがリクエストの前に実行されるか後に実行されるかは、ミドルウェア自体によって決まります。たとえば、次のミドルウェアは、リクエストがアプリケーションによって処理される

に何らかのタスクを実行します。

一中间件是在请求到达之前または者之後是要看中间件本身的,下面これは要求来の前に実行される

ただし、このミドルウェアは、アプリケーションによってリクエストが処理された後
< ?phpnamespace App\Http\Middleware;use Closure;class BeforeMiddleware   //明显的标志BeforeMiddleware{    public function handle($request, Closure $next)    {        // Perform action        return $next($request);    }}
にタスクを実行します:

ミドルウェアの登録

<?phpnamespace App\Http\Middleware;use Closure;class AfterMiddleware  //这是请求之后的{    public function handle($request, Closure $next)    {        $response = $next($request);        // Perform action        return $response;    }}
グローバル ミドルウェア

アプリケーションへのすべての HTTP リクエスト中にミドルウェアを実行したい場合は、app/ の $middlewareproperty にミドルウェア クラスをリストするだけです。 HTTP/Kernel.phpクラス。

必要な場合は、http 要求都の操作に対する中間ファイルの記述、単純な書き込み法、中間ファイルの app/Http/Kernel.php の

$middleware プロパティの場所、例:

ルートへのミドルウェアの割り当て
    protected $middleware = [        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,    ];

割り当てられた経路指定の中間コンポーネント、必要なアプリ/Http/Kernel.php 里(次の例)は中間コンポーネントです创建一短名,

ミドルウェアを特定のルートに割り当てたい場合は、まず app/Http/Kernel.php ファイルでミドルウェアに短縮キーを割り当てる必要があります。デフォルトでは、このクラスの $routeMiddleware プロパティには、Laravel に含まれるミドルウェアのエントリが含まれています。独自のキーを追加するには、それをこのリストに追加し、選択したキーを割り当てます。例:

ミドルウェアが HTTP カーネルで定義されたら、ルート オプション配列で middlewarekey を使用できます。
// Within App\Http\Kernel Class...protected $routeMiddleware = [    'auth' => \App\Http\Middleware\Authenticate::class, //就好像这样,将名字绑定中间件    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,];

配列を使用して、複数のミドルウェアをルートに割り当てます:

Route::get('admin/profile', ['middleware' => 'auth', function () {    //在路由里面就能够指定使用的中间件了 }]);

配列を使用する代わりに、ミドルウェア メソッドをルート定義にチェーンすることもできます:

Route::get('/', ['middleware' => ['first', 'second'], function () {    //分配多个中间件可以用数组}]);

ミドルウェアを割り当てるときに、次のように渡すこともできます。完全修飾クラス名:

Route::get('/', function () {    // 这里用链式方式写,使用middleware方法定义})->middleware(['first', 'second']); 

ミドルウェア グループ

use App\Http\Middleware\FooMiddleware;Route::get('admin/profile', ['middleware' => FooMiddleware::class, function () {    //传递一个完整的中间件类名,还需要加上use那部分,因为要寻找位置}]);

ルートへの割り当てを容易にするために、複数のミドルウェアを 1 つのキーの下にグループ化したい場合があります。これは、HTTP カーネルの $middlewareGroups プロパティを使用して行うことができます。

中间件组を使用、$middlewareGroups プロパティを使用

Laravel には、すぐに使える Web UI と API ルートに適用できる一般的なミドルウェアを含む Web バンド apimiddleware グループが付属しています。

默认laravel就在5.2版本提供了web和api的中间件组,他包含了普遍的中间件

/** * The application's route middleware groups. * * @var array */protected $middlewareGroups = [ //这里就是$middlewareGroups    'web' => [        \App\Http\Middleware\EncryptCookies::class,        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,        \Illuminate\Session\Middleware\StartSession::class,        \Illuminate\View\Middleware\ShareErrorsFromSession::class,        \App\Http\Middleware\VerifyCsrfToken::class,    ],//各自定义了一些中间件,例如一些cookie,session的中间件    'api' => [        'throttle:60,1',        'auth:api',    ],];

Middleware groups may be assigned to routes and controller actions using the same syntax as individual middleware. Again, middleware groups simply make it more convenient to assign many middleware to a route at once:使用相同的命令可以像使用单个中间件一样去将中间件组分配到路由或者控制器里,

Route::group(['middleware' => ['web']], function () {    //这里即使用了$middlewareGroups来编制中间件组,但是依然可以用单个中间件的使用方式来调用。});

Middleware Parameters

Middleware can also receive additional custom parameters. For example, if your application needs to verify that the authenticated user has a given “role” before performing a given action, you could create a RoleMiddlewarethat receives a role name as an additional argument.

中间件会收到额外的参数,举例,如果你的应用需要确认验证用户在执行动作之前已经有一个role,你应该建立一个 RoleMiddleware来接收这个额外的参数。

Additional middleware parameters will be passed to the middleware after the $nextargument:

额外的中间件参数会被传递到中间件的 $next的后面

< ?phpnamespace App\Http\Middleware;use Closure;class RoleMiddleware{    /**     * Run the request filter.     *     * @param  \Illuminate\Http\Request  $request     * @param  \Closure  $next     * @param  string  $role     * @return mixed     */    public function handle($request, Closure $next, $role) //增加了一个$role参数    {        if (! $request->user()->hasRole($role)) {            // Redirect...        }        return $next($request);    }}

Middleware parameters may be specified when defining the route by separating the middleware name and parameters with a :. Multiple parameters should be delimited by commas:

Route::put('post/{id}', ['middleware' => 'role:editor', function ($id) {    //用冒号分隔,中间件的名字:参数,这样也可以指定中间件的参数}]);

Terminable Middleware

有时候需要一个处理一些http回应已经发到浏览器之后的事情的中间件,例如session中间件包括了laravel写session数据并存储,在http回应发到浏览器之后,

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 afterthe response has been sent to the browser. To accomplish this, define the middleware as “terminable” by adding a terminatemethod to the middleware:

要实现这些,需要顶一个terminable中间件,增加一个terminate方法

<?phpnamespace Illuminate\Session\Middleware;use Closure;class StartSession{    public function handle($request, Closure $next)    {        return $next($request);    }    public function terminate($request, $response)    {        // Store the session data...  这个方法就是terminate方法,会接收请求和回应作为参数,当你已经定义一个这样的中间件的时候,你应该将它增加到全局的中间件列表里面去,kernel.php    }}

The terminatemethod should receive 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.

当中间件的 terminate方法调用的时候,laravel会从service container中分解一个fresh 中间件实例,如果handle和terminate方法被调用的时候,你使用一个相同的中间件实例的话,会使用这个container的singleton方法注册这个中间件

When calling the terminatemethod on your middleware, Laravel will resolve a fresh instance of the middleware from the service container. If you would like to use the same middleware instance when the handleand terminatemethods are called, register the middleware with the container using the container’s singletonmethod.

参考引用:

https://laravel.com/docs/5.2/middleware

http://laravelacademy.org/post/2803.html

本文由 PeterYuan 创作,采用 署名-非商业性使用 2.5 中国大陆 进行许可。 转载、引用前需联系作者,并署名作者且注明文章出处。神一样的少年 » laravel5.2-http middleware学习

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。