laravel5.2-http middleware學習

來源:互聯網
上載者:User

HTTP Middleware

Introduction

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.

Of course, additional 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.

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/Middlewaredirectory.

Defining Middleware

To create a new middleware, use the make:middlewareArtisan command:

建立中介軟體可以使用工具建立,artisan是個協助你建立一些中介軟體或者其他的好工具,

php artisan make:middleware AgeMiddleware

這個命令會建立一個中介軟體(其實是一個class)在你的 app/Http/Middleware目錄裡面,並且檔案裡面已經包含了一些寫好的模板,例如這裡,

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    }}//這個只是預設範例。

This command will place a new AgeMiddlewareclass within your app/Http/Middlewaredirectory. In this middleware, we will only allow access to the route if the supplied ageis greater than 200. Otherwise, we will redirect the users back to the “home” URI.

這個中介軟體是修改過的,改成只允許支援age大於200的請求進入路由,否則重新導向到home頁面

input('age') < = 200) {//調用input方法,並且傳入參數age,            return redirect('home');        }        return $next($request);    }}

As you can see, if the given ageis less than or equal to 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 $nextcallback 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.

Before/ AfterMiddleware

Whether a middleware runs before or after a request depends on the middleware itself. For example, the following middleware would perform some task beforethe request is handled by the application:

一個中介軟體是在請求到達之前或者之後是要看中介軟體本身的,下面這個是在請求來之前執行的

< ?phpnamespace App\Http\Middleware;use Closure;class BeforeMiddleware   //明顯的標誌BeforeMiddleware{    public function handle($request, Closure $next)    {        // Perform action        return $next($request);    }}

However, this middleware would perform its task afterthe request is handled by the application:

   

Registering Middleware

Global Middleware

If you want a middleware to be run during every HTTP request to your application, simply list the middleware class in the $middlewareproperty of your app/Http/Kernel.phpclass.

如果需要中介軟體對每個http請求都操作的話,簡單的寫法是,將中介軟體寫在 app/Http/Kernel.php的

$middleware屬性裡面,例如

    protected $middleware = [        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,    ];

Assigning Middleware To Routes

分配給路由的中介軟體,需要在你的app/Http/Kernel.php裡(如下例)為中介軟體建立一個短名,

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.phpfile. By default, the $routeMiddlewareproperty 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. For example:

// 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,];

Once the middleware has been defined in the HTTP kernel, you may use the middlewarekey in the route options array:

Route::get('admin/profile', ['middleware' => 'auth', function () {    //在路由裡面就能夠指定使用的中介軟體了 }]);

Use an array to assign multiple middleware to the route:

Route::get('/', ['middleware' => ['first', 'second'], function () {    //分配多個中介軟體可以用數組}]);

Instead of using an array, you may also chain the middlewaremethod onto the route definition:

Route::get('/', function () {    // 這裡用鏈式方式寫,使用middleware方法定義})->middleware(['first', 'second']); 

When assigning middleware, you may also pass the fully qualified class name:

use App\Http\Middleware\FooMiddleware;Route::get('admin/profile', ['middleware' => FooMiddleware::class, function () {    //傳遞一個完整的中介軟體類名,還需要加上use那部分,因為要尋找位置}]);

Middleware Groups

Sometimes you may want to group several middleware under a single key to make them easier to assign to routes. You may do this using the $middlewareGroupsproperty of your HTTP kernel.

使用中介軟體組,使用 $middlewareGroups屬性

Out of the box, Laravel comes with weband apimiddleware groups that contains common middleware you may want to apply to web UI and your API routes:

預設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方法

   

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學習

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.