欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

Laravel 5.0 - Middleware (中间件)

shiping1 的头像

image

图片:http://stackphp.com/

如上图所示,中心的绿色区域是整个应用的核心区域。

所以,中间件就是一系列处理请求和响应的方式而不是你用程序逻辑的一部分。

Laravel 中默认使用中间件处理请求中的加密解密,以及 Cookies 和 Sessions。你也可以自定义自己所需的中间件。

写中间件

artisan make:middleware MyMiddleware

执行上面的命令,生成中间件文件:

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Routing\Middleware;

class MyMiddleware implements Middleware {

    /**
    * Handle an incoming request.
    *
    * @param  \Illuminate\Http\Request  $request
    * @param  \Closure  $next
    * @return mixed
    */
    public function handle($request, Closure $next)
    {
        //
    }

}

完善 handle 方法的内容(用请求端口来做个例子):

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Routing\Middleware;

class MyMiddleware implements Middleware {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // Test for an even vs. odd remote port
        if (($request->server->get('REMOTE_PORT') / 2) % 2 > 0)
        {
            throw new \Exception("WE DON'T LIKE ODD REMOTE PORTS");
        }

        return $next($request);
    }

}

使用中间件

Laravel 5 中有两种方法加入中间件,都是写在 App\Providers\AppServiceProvider。

默认有两个属性 $middleware 和 $stack ,$stack 里面的中间件是每次响应都会处理,而 $middleware 中的中间件是按需处理。

一帮情况下默认的中间件如下:

protected $stack = [
        'App\Http\Middleware\MaintenanceMiddleware',
        'Illuminate\Cookie\Middleware\Guard',
        'Illuminate\Cookie\Middleware\Queue',
        'Illuminate\Session\Middleware\Reader',
        'Illuminate\Session\Middleware\Writer',
    ];

protected $middleware = [
        'auth' = 'App\Http\Middleware\AuthMiddleware',
        'auth.basic' => 'App\Http\Middleware\BasicAuthMiddleware',
        'csrf' => 'App\Http\Middleware\CsrfMiddleware',
        'guest' => 'App\Http\Middleware\GuestMiddleware',
    ];    

中间件每次请求都处理:

protected $stack = [
        'App\Http\Middleware\MyMiddleware'
        'App\Http\Middleware\MaintenanceMiddleware',
        'Illuminate\Cookie\Middleware\Guard',
        'Illuminate\Cookie\Middleware\Queue',
        'Illuminate\Session\Middleware\Reader',
        'Illuminate\Session\Middleware\Writer',
    ];

中间件按需处理:

 protected $middleware = [
        'auth' => 'App\Http\Middleware\AuthMiddleware',
        'auth.basic' => 'App\Http\Middleware\BasicAuthMiddleware',
        'csrf' => 'App\Http\Middleware\CsrfMiddleware',
        'guest' => 'App\Http\Middleware\GuestMiddleware',
        'absurd' => 'App\Http\Middleware\MyMiddleware',
    ];

中间件路由注释

直接写到控制器类:

/**
 * @Resource("foobar/photos")
 * @Middleware("auth")
 * @Middleware("absurd", except={"update"})
 * @Middleware("csrf", only={"index"})
 */
class FoobarPhotosController
{}

写到方法:

/**
 * @Middleware("auth.basic")
 */
public function index() {}

$this->middleware()

可以在构造函数或者方法内使用 $this->middleware() 来加载相应的中间件。

...
use Illuminate\Routing\Controller;

class AwesomeController extends Controller {

    public function __construct()
    {
        $this->middleware('csrf');
        $this->middleware('auth', ['only' => 'update'])
    }

}

routes.php 设置中间件

// Routes.php

// Single route
$router->get("/awesome/sauce", "AwesomeController@sauce", ['middleware' => 'auth']);

// Route group
$router->group(['middleware' => 'auth'], function() {
    // lots of routes that require auth middleware
});

响应之前和之后处理

应用程序响应之前和之后的中间件处理:

之前处理:

...
class BeforeMiddleware implements Middleware {

    public function handle($request, Closure $next)
    {
        // Do Stuff
        return $next($request);
    }

}

之后处理:

...
class AfterMiddleware implements Middleware {

    public function handle($request, Closure $next)
    {
        $response = $next($request);
        // Do stuff
        return $response;
    }

}

Original :http://mattstauffer.co/blog/laravel-5.0-middleware-replacing-filters

来自 http://laravel.lapland.name/post/103009889055/laravel-5-0-middleware-replacing-filters

普通分类: