Laravel中间件原理

简介

Laravel 中间件提供了一种方便的机制来过滤进入应用的 HTTP 请求, 如ValidatePostSize用来验证POST请求体大小、ThrottleRequests用于限制请求频率等。php

那Laravel的中间件是怎样工做的呢?laravel

启动流程

再说Laravel中间件前,咱们先来理一理laravel的启动流程bootstrap

首先,入口文件index.php加载了autoload和引导文件bootstrap数组

require __DIR__.'/../bootstrap/autoload.php';

$app = require_once __DIR__.'/../bootstrap/app.php';

并在引导文件bootstrap/app.php中初始化了Application实例session

$app = new Illuminate\Foundation\Application(
    realpath(__DIR__.'/../')
);

咱们先跳过如何初始化Application(后面会有简单介绍),再回到入口文件(index.php)中,经过从Application实例$app中获取Http Kernel对象来执行handle方法,换取responseapp

$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

$response->send();
$kernel->terminate($request, $response);

换取响应后,把响应内容返回给Client,并执行后续操做(terminate,如关闭session等)。ide

实例化Application函数

Laravel的容器并非我此次说的重点,这里简单介绍下post

在初始化Application(启动容器)时,Laravel主要作了三件事情ui

  1. 注册基础绑定

  2. 注册基础服务提供者

  3. 注册容器核心别名

注册完成之后,咱们就能直接从容器中获取须要的对象(如Illuminate\\Contracts\\Http\\Kernel),即便它是一个Interface

获取Illuminate\Contracts\Http\Kernel类时,咱们获得的真正实例是 AppHttpKernel

// bootstrap/app.php

$app->singleton(
    Illuminate\Contracts\Http\Kernel::class,
    App\Http\Kernel::class
);

Laravel容器请参考

Handle

从容器中得到Http Kernel对象后,Laravel经过执行kernel->handle来换取response对象。

//Illuminate\Foundation\Http\Kernel.php

public function handle($request)
{
    $request->enableHttpMethodParameterOverride();
    $response = $this->sendRequestThroughRouter($request);
    //......
}

enableHttpMethodParameterOverride方法开启方法参数覆盖,便可以在POST请求中添加_method参数来伪造HTTP方法(如post中添加_method=DELETE来构造HTTP DELETE请求)。

而后Laravel把请求对象(request)经过管道流操做。

protected function sendRequestThroughRouter($request)
{
    return (new Pipeline($this->app))
        ->send($request)
        ->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware)
        ->then($this->dispatchToRouter());
}

/**
 * Get the route dispatcher callback.
 *
 * @return \Closure
 */
protected function dispatchToRouter()
{
    return function ($request) {
        $this->app->instance('request', $request);
        return $this->router->dispatch($request);
    };
}

Pipeline是laravel的管道操做类。在这个方法中,个人理解是:发送一个$request对象经过middleware中间件数组,最后在执行dispatchToRouter方法。注意,这里的中间件只是全局中间件。即首先让Request经过全局中间件,而后在路由转发中($this->dispatchToRouter()),再经过路由中间件中间件group

因此,到这里为止,Laravel的请求交给了Pipeline管理,让咱们来看看这个Pipeline到底是怎样处理的。

//Illuminate\Pipeline\Pipeline.php

public function then(Closure $destination)
{
    $pipeline = array_reduce(
        array_reverse($this->pipes), $this->carry(), $this->prepareDestination($destination)
    );
    return $pipeline($this->passable);
}

protected function prepareDestination(Closure $destination)
{
    return function ($passable) use ($destination) {
        return $destination($passable);
    };
}
 
protected function carry()
{
    return function ($stack, $pipe) {
        return function ($passable) use ($stack, $pipe) {
            if ($pipe instanceof Closure) {
                return $pipe($passable, $stack);
            } elseif (! is_object($pipe)) {
                list($name, $parameters) = $this->parsePipeString($pipe);
                $pipe = $this->getContainer()->make($name);
                $parameters = array_merge([$passable, $stack], $parameters);
            } else {
                $parameters = [$passable, $stack];
            }
            return $pipe->{$this->method}(...$parameters);
        };
    };
}

咱们来看看最重要的then方法, 在这方法中$destination表示经过该管道最后要执行的Closure(即上述的dispatchToRouter方法)。passable表示被经过管道的对象Request

php内置方法array_reduce把全部要经过的中间件($this->pipes)都经过carry方法($this->pipes不为空时)并压缩为一个Closure。最后在执行prepareDestination

array_reduce($pipes, callback($stack, $pipe), $destination), 当pipes为空时,直接执行destination,不然将全部$pipes压缩为一个Closure,最后在执行destination

列如我有两个中间件

Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
App\Http\Middleware\AllowOrigin::class,//自定义中间件

将这两个中间件经过array_reduce方法时,返回压缩后Closure如:

Laravel中间件原理

Closure共有三个层, 前面两个为两个中间件,后面个位最后要执行的Closure(即上述的dispatchToRouter方法)。

//中间件handle
public function handle($request, Closure $next)
{
}

在第一个经过的中间件(此处是CheckForMaintenanceModehandle方法中,dump($next)以下

Laravel中间件原理

在第二个经过的中间件(共两个,此处是AllowOriginhandle方法中,dump($next)以下

Laravel中间件原理

由此可知,中间件在执行$next($request)时,表示该中间件已正常经过,并期待继续执行下一个中间件。直到全部中间件都执行完毕,最后在执行最后的destination(即上述的dispatchToRouter方法)

若是上述array_reduce有地方难懂的,能够参考这边文章PHP 内置函数 array_reduce 在 Laravel 中的使用

以上是Laravel在经过全局中间件时的大体流程,经过中间件group和路由中间件也是同样的, 都是采用管道流操做,详情可翻阅源码

Illuminate\Routing\Router->runRouteWithinStack


godruoyi.png

相关文章
相关标签/搜索