[关闭]
@fzbing 2015-07-10T10:44:34.000000Z 字数 2332 阅读 1309

HTTP 中间件

学习笔记之Lumen


简介

HTTP中间件提供了一个方便的机制过滤进入应用的请求.例如,Lumen包含了一个验证CSRF token的中间件.

当然,除了CSRF验证,中间件可以被用来执行多种任务.CORS中间件负责为应用的response添加合适的header.logging中间件可以用来记录所有进入应用的请求.

所有的中间件通常位于app/Http/Middleware目录.

定义中间件

要创建一个中间件,简单的创建一个拥有一个handle方法类:

  1. public function handle($request, $next)
  2. {
  3. return $next($request);
  4. }

For example, let's create a middleware that 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.

举例,让我们创建一个中间件,只在提供的age大于200时允许访问路由.否则,我们会将用户重新导向 home URI

  1. <?php namespace App\Http\Middleware;
  2. class OldMiddleware {
  3. /**
  4. * Run the request filter.
  5. *
  6. * @param \Illuminate\Http\Request $request
  7. * @param \Closure $next
  8. * @return mixed
  9. */
  10. public function handle($request, Closure $next)
  11. {
  12. if ($request->input('age') < 200) {
  13. return redirect('home');
  14. }
  15. return $next($request);
  16. }
  17. }

如你所见,若是 年龄 小于 200 ,中间件将会返回 HTTP重定向给客户端,否则,请求将会进一步传递到应用程序。只需调用带有 requestnext 方法,即可将请求传递到更深层的应用程序(允许跳过中间件).

HTTP 请求在实际碰触到应用程序之前,最好是可以层层通过许多中间件,每一层都可以对请求进行检查,甚至是完全拒绝请求。

Before / After Middleware

一个中间件运行在请求前后依赖于它自身.
这个中间件在请求被处理之前执行一些任务

  1. <?php namespace App\Http\Middleware;
  2. class BeforeMiddleware implements Middleware {
  3. public function handle($request, Closure $next)
  4. {
  5. // Perform action
  6. return $next($request);
  7. }
  8. }

然而,这个中间件执行它的任务在请求被处理之后.

  1. <?php namespace App\Http\Middleware;
  2. class AfterMiddleware implements Middleware {
  3. public function handle($request, Closure $next)
  4. {
  5. $response = $next($request);
  6. // Perform action
  7. return $response;
  8. }
  9. }

注册中间件

全局中间件

如果你想在每一次HTTP请求时运行一个中间件,仅仅需要在bootstrap/app.php文件用的$app->middleware()中列出你的中间件类.

指派中间件给路由

如果你想要为特定的路由指定中间件,你应该首先在bootstrap/app.php文件中为中间件指定一个简短的key.

系统默认用$app->routeMiddleware()方法包含一些中间件.要添加自己的中间件,简单的追加在这个列表,并指定一个key.例如:

  1. $app->routeMiddleware([
  2. 'old' => 'App\Http\Middleware\OldMiddleware',
  3. ]);

一旦这个中间件被定义进HTTP kernel,你可以在路由options array应用中间件key:

  1. $app->get('admin/profile', ['middleware' => 'old', function() {
  2. //
  3. }]);

可终止中间件

有些时候中间件需要在 HTTP 响应已被发送到用户端之后才执行,例如,Laravel 和Lumen 内置的 session 中间件,保存 session 数据是在响应已被发送到用户端之后才执行。为了做到这一点,你需要定义继承 Illuminate\Contracts\Routing\TerminableMiddleware的中间件。

  1. use Illuminate\Contracts\Routing\TerminableMiddleware;
  2. class StartSession implements TerminableMiddleware {
  3. public function handle($request, $next)
  4. {
  5. return $next($request);
  6. }
  7. public function terminate($request, $response)
  8. {
  9. // Store the session data...
  10. }
  11. }

如你所见,除了定义 handle 方法之外, TerminableMiddleware 定义一个 terminate 方法。这个方法接收请求和响应。一旦定义了 terminable 中间件,你需要将它增加到 HTTP kernel 的全局中间件清单列表中。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注