Laravel 中介軟體原理

godruoyi發表於2017-07-05

簡介

Laravel 中介軟體提供了一種方便的機制來過濾進入應用的 HTTP 請求, 如ValidatePostSize用來驗證POST請求體大小、ThrottleRequests用於限制請求頻率等。

那Laravel的中介軟體是怎樣工作的呢?

啟動流程

再說Laravel中介軟體前,我們先來理一理laravel的啟動流程

首先,入口檔案index.php載入了autoload和引導檔案bootstrap

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

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

並在引導檔案bootstrap/app.php中初始化了Application例項

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

我們先跳過如何初始化Application(後面會有簡單介紹),再回到入口檔案(index.php)中,通過從Application例項$app中獲取Http Kernel物件來執行handle方法,換取response

$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等)。

例項化Application

Laravel的容器並不是我這次說的重點,這裡簡單介紹下

在初始化Application(啟動容器)時,Laravel主要做了三件事情

  1. 註冊基礎繫結
  2. 註冊基礎服務提供者
  3. 註冊容器核心別名

註冊完成以後,我們就能直接從容器中獲取需要的物件(如Illuminate\\Contracts\\Http\\Kernel),即使它是一個Interface

獲取Illuminate\Contracts\Http\Kernel類時,我們得到的真正例項是 App\Http\Kernel

// 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如:

file

Closure共有三個層, 前面兩個為兩個中介軟體,後面個位最後要執行的Closure(即上述的dispatchToRouter方法)。

//中介軟體handle
public function handle($request, Closure $next)
{
}

在第一個通過的中介軟體(此處是CheckForMaintenanceModehandle方法中,dump($next)如下

file

在第二個通過的中介軟體(共兩個,此處是AllowOriginhandle方法中,dump($next)如下

file

由此可知,中介軟體在執行$next($request)時,表示該中介軟體已正常通過,並期待繼續執行下一個中介軟體。直到所有中介軟體都執行完畢,最後在執行最後的destination(即上述的dispatchToRouter方法)

如果上述array_reduce有地方難懂的,可以參考這邊文章PHP 內建函式 array_reduce 在 Laravel 中的使用

以上是Laravel在通過全域性中介軟體時的大致流程,通過中介軟體group和路由中介軟體也是一樣的, 都是採用管道流操作,詳情可翻閱原始碼

Illuminate\Routing\Router->runRouteWithinStack


二楞徐的閒談雜魚

相關文章