Laravel 5.0

WBOY
Lepaskan: 2016-06-20 12:47:53
asal
839 orang telah melayarinya

图片: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)    {        //    }}
Salin selepas log masuk

完善 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);    }}
Salin selepas log masuk

使用中间件

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',    ];
Salin selepas log masuk

中间件每次请求都处理:

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',    ];
Salin selepas log masuk

中间件按需处理:

 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',    ];
Salin selepas log masuk

中间件路由注释

直接写到控制器类:

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

写到方法:

/** * @Middleware("auth.basic") */public function index() {}
Salin selepas log masuk

$this->middleware()

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

...use Illuminate\Routing\Controller;class AwesomeController extends Controller {    public function __construct()    {        $this->middleware('csrf');        $this->middleware('auth', ['only' => 'update'])    }}
Salin selepas log masuk

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});
Salin selepas log masuk

响应之前和之后处理

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

之前处理:

...class BeforeMiddleware implements Middleware {    public function handle($request, Closure $next)    {        // Do Stuff        return $next($request);    }}
Salin selepas log masuk

之后处理:

...class AfterMiddleware implements Middleware {    public function handle($request, Closure $next)    {        $response = $next($request);        // Do stuff        return $response;    }}
Salin selepas log masuk


sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan