Laravel学習ノートのMiddlewareソース解析


説明:本文は主にLaravelのMiddlewareのソースコードの設計思想を勉強して、そして学習の心得を分かち合って、他の人に役に立つことを望みます.Laravel学習ノートのDecorator Pattern LavelはDecorator Patternを使用してMiddlewareを設計することについて話しています.Laravelソースコードを見ると、ClosureとPHPのいくつかの配列関数を巧みに使用してMiddlewareを設計していることがわかります. :Laravel5.3 + PHP7 + OS X 10.11
PHP内蔵関数array_reverse、array_reduce、call_user_funcとcall_user_func_array
Laravelソースコードを見る前に、これらのPHP内蔵関数の使用を見てみましょう.まずはarray_reverse()関数は比較的簡単で、配列を逆さまにして、テストコードを見ます:
$pipes = [
    'Pipe1',
    'Pipe2',
    'Pipe3',
    'Pipe4',
    'Pipe5',
    'Pipe6',
];

$pipes = array_reverse($pipes);

var_dump($pipes);

// output
array(6) {
  [0] =>
  string(5) "Pipe6"
  [1] =>
  string(5) "Pipe5"
  [2] =>
  string(5) "Pipe4"
  [3] =>
  string(5) "Pipe3"
  [4] =>
  string(5) "Pipe2"
  [5] =>
  string(5) "Pipe1"
}

array_reduce内蔵関数は、主にコールバック関数を使用して配列内の各値、 を反復し、最終反復の値を返します.
/**
 * @link http://php.net/manual/zh/function.array-reduce.php
 * @param int $v
 * @param int $w
 *
 * @return int
 */
function rsum($v, $w)
{
    $v += $w;
    return $v;
}

$a = [1, 2, 3, 4, 5];
// 10    
$b = array_reduce($a, "rsum", 10);
//      (((((10 + 1) + 2) + 3) + 4) + 5) = 25
echo $b . PHP_EOL; 

call_user_func()は、コールバック関数を実行し、テストコードを参照して、コールバック関数のパラメータとしてパラメータを入力できます.
class TestCallUserFunc
{
    public function index($request)
    {
        echo $request . PHP_EOL;
    }
}   

/**
 * @param $test
 */
function testCallUserFunc($test)
{
    echo $test . PHP_EOL;
}

// [$class, $method]
call_user_func(['TestCallUserFunc', 'index'], 'pipes'); //   'pipes'

// Closure
call_user_func(function ($passable) {
    echo $passable . PHP_EOL;
}, 'pipes'); //   'pipes'

// function
call_user_func('testCallUserFunc' , 'pipes'); //   'pipes'

call_user_func_arrayとcall_user_funcは基本的に同じですが、入力されたパラメータは配列です.
class TestCallUserFuncArray
{
    public function index($request)
    {
        echo $request . PHP_EOL;
    }
}

/**
 * @param $test
 */
function testCallUserFuncArray($test)
{
    echo $test . PHP_EOL;
}

// [$class, $method]
call_user_func_array(['TestCallUserFuncArray', 'index'], ['pipes']); //   'pipes'

// Closure
call_user_func_array(function ($passable) {
    echo $passable . PHP_EOL;
}, ['pipes']); //   'pipes'

// function
call_user_func_array('testCallUserFuncArray' , ['pipes']); //   'pipes'

Middlewareソースの解析
いくつかのPHP内蔵関数を知ってからMiddlewareソースコードを見ると簡単です.Laravel学習ノートのIoC Containerインスタンス化ソース解析既にApplicationのインスタンス化について話し、indexを得る.phpの$app変数、すなわちIlluminateFoundationApplicationのインスタンス化されたオブジェクト.そしてindexを見続けます.phpのソース:
/**
 * @var \App\Http\Kernel $kernel
 */
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

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

$response->send();

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

まず,コンテナからKernelオブジェクトを解析し,AppHttpKernelオブジェクトへの依存:IlluminateFoundationApplicationとIlluminateRoutingRouterに対してコンテナは自動解析する.Kernelの構造関数を見てみましょう.
    /**
     * Create a new HTTP kernel instance.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @param  \Illuminate\Routing\Router  $router
     */
    public function __construct(Application $app, Router $router)
    {
        $this->app    = $app;
        $this->router = $router;

        foreach ($this->middlewareGroups as $key => $middleware) {
            $router->middlewareGroup($key, $middleware);
        }

        foreach ($this->routeMiddleware as $key => $middleware) {
            $router->middleware($key, $middleware);
        }
    }
    
    // \Illuminate\Routing\Router    
    public function middlewareGroup($name, array $middleware)
    {
        $this->middlewareGroups[$name] = $middleware;

        return $this;
    }
    
    public function middleware($name, $class)
    {
        $this->middleware[$name] = $class;

        return $this;
    }

コンストラクション関数はいくつかのミドルウェア配列,$middleware[],$middlewareGroup[]および$routeMiddleware[],Laravel 5を初期化した.0のとき、ミドルウェアの配列がこんなに細かく分かれていないことを覚えています.次に、Requestのインスタンス化です.

$request = Illuminate\Http\Request::capture()

この過程は後で話しましょう.いずれにしても、IlluminateHttpRequestオブジェクトを手に入れて、Kernelに伝えます.
    /**
     * Handle an incoming HTTP request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function handle($request)
    {
        try {
            $request->enableHttpMethodParameterOverride();

            $response = $this->sendRequestThroughRouter($request);
        } catch (Exception $e) {
            $this->reportException($e);

            $response = $this->renderException($request, $e);
        } catch (Throwable $e) {
            $this->reportException($e = new FatalThrowableError($e));

            $response = $this->renderException($request, $e);
        }

        $this->app['events']->fire('kernel.handled', [$request, $response]);

        return $response;
    }

主にsendRequestThroughRouter($request)関数は、IlluminateHttpRequestオブジェクトをIlluminateHttpResponseに変換し、Kernelのsend()メソッドでクライアントに送信する変換操作を実行します.同時にkernelがトリガーされた.handledカーネルはリクエストイベントを処理しました.OK、sendRequestThroughRouter($request)メソッドに注目:
    /**
     * Send the given request through the middleware / router.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    protected function sendRequestThroughRouter($request)
    {
        $this->app->instance('request', $request);

        Facade::clearResolvedInstance('request');

        /*     $bootstrappers    bootstrapper bootstrap()  ,        :
        1.     
        2.     
        3.     
        4.     
        5.   Facades
        6.   Providers
        7.     
         protected $bootstrappers = [
            'Illuminate\Foundation\Bootstrap\DetectEnvironment',
            'Illuminate\Foundation\Bootstrap\LoadConfiguration',
            'Illuminate\Foundation\Bootstrap\ConfigureLogging',
            'Illuminate\Foundation\Bootstrap\HandleExceptions',
            'Illuminate\Foundation\Bootstrap\RegisterFacades',
            'Illuminate\Foundation\Bootstrap\RegisterProviders',
            'Illuminate\Foundation\Bootstrap\BootProviders',
        ];*/
        $this->bootstrap();

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

$this->bootstrap()は主にプログラムの初期化を行い、後で具体的な詳細を話します.次にPipelineでRequestを転送し、LaravelではPipeline を単独でサービスとして取り出し(Illuminate/Pipelineフォルダを参照)、Pipelineが行うことが重要であることを説明します.主にRequestの転送パイプとして、$middlewares[]、またはmiddlewareGroup[]、または$routeMiddleware[]の中間部品の前置き操作を順次通過します.コントローラのactionまたは直接閉パケット処理によってResponseが得られ、その後、Reponseを伴って$middlewares[]またはmiddlewareGroup[]または$routeMiddleware[]の中間部品の後置操作によって準備されたResponseが得られ、send()によってクライアントに送信される.この過程は少し自動車工場の生産のように、Pipelineはコンベアで、最初はRequestは自動車の空殻かもしれませんが、コンベアのそばを通るロボットの一人一人です.middleware@beforeの濾過と操作(例えば部品の剛性が合格しているかどうかを検査して、殻のサイズが要求に合っているかどうかを検査して、殻にペンキを塗ったり油を塗ったりして)、それから中央制御区に入ってエンジン(Controller @action、あるいはClosure)をプラスして、それからまた検査と添付操作を続けますmiddleware@after(フロントミラーを追加するなど)、ドアの外で待っている列車を通じて消費者の手に直接運ばれますsend()各ステップのアセンブリでは、サービスがサポートされる必要があります.サービスはContainerによって{make()}を解析して提供され、サービスはサービスプロバイダ登録バインディング{bind(),singleton(),instance()}によってContainerに登録されます.
Pipelineのsend()とthrough()のソースコードを見てください.
    public function send($passable)
    {
        $this->passable = $passable;

        return $this;
    }
    
    public function through($pipes)
    {
        $this->pipes = is_array($pipes) ? $pipes : func_get_args();

        return $this;
    }

send()が転送するオブジェクトはRequest、through()が通過するオブジェクトは$middleware[]で、OKです.dispatchToRouter()のソースコードを見て、Closureを直接返します.
    protected function dispatchToRouter()
    {
        return function ($request) {
            $this->app->instance('request', $request);

            return $this->router->dispatch($request);
        };
    }

次にthen()関数のソースコードに重点を置きます.
    public function then(Closure $destination)
    {
        $firstSlice = $this->getInitialSlice($destination);

        $pipes = array_reverse($this->pipes);

        // $this->passable = Request  
        return call_user_func(
            array_reduce($pipes, $this->getSlice(), $firstSlice), $this->passable
        );
    }
    
    protected function getInitialSlice(Closure $destination)
    {
        return function ($passable) use ($destination) {
            return call_user_func($destination, $passable);
        };
    }

ここで、$middlewaresは(ソースコードの$middlewaresにはCheckForMaintenanceModeが1つしかないにもかかわらず):
$middlewares = [
    CheckForMaintenanceMode::class,
    AddQueuedCookiesToResponse::class,
    StartSession::class,
    ShareErrorsFromSession::class,
    VerifyCsrfToken::class,
];

まず最初のslice(ここで著者は「玉ねぎ」にたとえ、一重に通り抜け、片側から反対側に通り抜け、比喩もイメージしている)を取得し、arrayとして使用します.reduce()の初期値は、前述のarray_のようにreduce()テスト例の10という初期値、この初期値は現在閉パケットです.
$destination = function ($request) {
    $this->app->instance('request', $request);
    return $this->router->dispatch($request);
};

$firstSlice = function ($passable) use ($destination) {
    return call_user_func($destination, $passable);
};

OK、そして$middlewares[]を反転します.なぜ反転しますか?このLaravel学習ノートのDecorator Patternの記事を見ると、ClientクラスがDecorator Patternを利用して順番に装飾されている場合、$middlewares[]配列の値に従ってnewが逆さまになっていることがわかります.
    public function wrapDecorator(IMiddleware $decorator)
    {
        $decorator = new VerifyCsrfToken($decorator);
        $decorator = new ShareErrorsFromSession($decorator);
        $decorator = new StartSession($decorator);
        $decorator = new AddQueuedCookiesToResponse($decorator);
        $response  = new CheckForMaintenanceMode($decorator);

        return $response;
    }

$middlewares[]の順序に一致する$responseオブジェクトが得られます.
$response = new CheckForMaintenanceMode(
                new AddQueuedCookiesToResponse(
                    new StartSession(
                        new ShareErrorsFromSession(
                            new VerifyCsrfToken(
                                new Request()
                        )
                    )
                )
            )
        );

arrayを見てreduce()の反復コールバック関数getSlice(){この反復コールバック関数は、タマネギを剥くときにタマネギsliceの各層を取得することにたとえられ、初期値は$firstSlice}:
    protected function getSlice()
    {
        return function ($stack, $pipe) {
            return function ($passable) use ($stack, $pipe) {
                if ($pipe instanceof Closure) {
                    return call_user_func($pipe, $passable, $stack);
                } elseif (! is_object($pipe)) {
                    list($name, $parameters) = $this->parsePipeString($pipe);
                    $pipe = $this->container->make($name);
                    $parameters = array_merge([$passable, $stack], $parameters);
                } else{
                    $parameters = [$passable, $stack];
                }

                return call_user_func_array([$pipe, $this->method], $parameters);
            };
        };
    }

戻りは閉パケットです.2番目のレイヤの閉パケットの論理をよく見てください.ここで$middlewares[]は各ミドルウェアの名前を入力し、コンテナを通じて各ミドルウェアオブジェクトを解析します.
$pipe = $this->container->make($name);

そして最後にcall_user_func_array([$class,$method],array$parameters)は、この$classの$methodメソッドを呼び出します.パラメータは$parametersです.
Demo
次にdemoを書いて流れ全体を見てみましょう.まずgetSlice()関数を簡略化します.ここでデフォルト$pipeはクラス名(demo全体のすべてのclassが同じファイル内にある)を入力します.
// PipelineTest.php

// Get the slice in every step.
function getSlice()
{
    return function ($stack, $pipe) {
        return function ($passable) use ($stack, $pipe) {
            /**
             * @var Middleware $pipe
             */
            return call_user_func_array([$pipe, 'handle'], [$passable, $stack]);
        };
    };
}

さらに$middlewares[]の5つのミドルウェアクラスを書き、前置操作と後置操作を簡略化し、直接echo文字列を作成します.
// PipelineTest.php


完全なPipelineクラスを与えて、ここのPipelineはLaravelの中のPipelineに対して少し簡略化して、いくつかの重要な関数だけを選択しました:
// PipelineTest.php

class Pipeline 
{
    /**
     * @var array
     */
    protected $middlewares = [];

    /**
     * @var int
     */
    protected $request;

    // Get the initial slice
    function getInitialSlice(Closure $destination)
    {
        return function ($passable) use ($destination) {
            return call_user_func($destination, $passable);
        };
    }
    
    // Get the slice in every step.
    function getSlice()
    {
        return function ($stack, $pipe) {
            return function ($passable) use ($stack, $pipe) {
                /**
                 * @var Middleware $pipe
                 */
                return call_user_func_array([$pipe, 'handle'], [$passable, $stack]);
            };
        };
    }
    
    // When process the Closure, send it as parameters. Here, input an int number.
    function send(int $request)
    {
        $this->request = $request;
        return $this;
    }

    // Get the middlewares array.
    function through(array $middlewares)
    {
        $this->middlewares = $middlewares;
        return $this;
    }
    
    // Run the Filters.
    function then(Closure $destination)
    {
        $firstSlice = $this->getInitialSlice($destination);
    
        $pipes = array_reverse($this->middlewares);
        
        $run = array_reduce($pipes, $this->getSlice(), $firstSlice);
    
        return call_user_func($run, $this->request);
    }
}

OK、Requestが転送されます.ここでは、Requestオブジェクトではなく整数に簡略化されます.
// PipelineTest.php

/**
 * @return \Closure
 */
function dispatchToRouter()
{
    return function ($request) {
        echo $request . ': Send Request to the Kernel, and Return Response.' . PHP_EOL;
    };
}

$request = 10;

$middlewares = [
    CheckForMaintenanceMode::class,
    AddQueuedCookiesToResponse::class,
    StartSession::class,
    ShareErrorsFromSession::class,
    VerifyCsrfToken::class,
];

(new Pipeline())->send($request)->through($middlewares)->then(dispatchToRouter());
php PipelineTest.phpを実行してResponseを得る:
10: Check if the application is in the maintenance status.
10: Start session of this request.
10: Verify csrf token when post request.
10: Send Request to the Kernel, and Return Response.
10: Share the errors variable from response to the views.
10: Close session of this response.
10: Add queued cookies to the response.

手順を1つずつ分析して実行します.
1.まず$firstSliceを取得
$destination = function ($request) {
    echo $request . ': Send Request to the Kernel, and Return Response.' . PHP_EOL;
};
$firstSlice = function ($passable) use ($destination) {
    return call_user_func($destination, $passable);
};

初期化後:
$this->request = 10;
$pipes = [
    VerifyCsrfToken::class,
    ShareErrorsFromSession::class,
    StartSession::class,
    AddQueuedCookiesToResponse::class,
    CheckForMaintenanceMode::class,
];

2.最初のgetSlice()を実行した後の結果を新しい$stackとして、その値は:
$stack   = $firstSlice;
$pipe    = VerifyCsrfToken::class;
$stack_1 = function ($passable) use ($stack, $pipe) {
        /**
        * @var Middleware $pipe
        */            
    return call_user_func_array([$pipe, 'handle'], [$passable, $stack]);
};

3.2回目のgetSlice()を実行した結果、新しい$stackとして、次の値が得られます.
$stack   = $stack_1;
$pipe    = ShareErrorsFromSession::class;
$stack_2 = function ($passable) use ($stack, $pipe) {
        /**
        * @var Middleware $pipe
        */            
    return call_user_func_array([$pipe, 'handle'], [$passable, $stack]);
};

4.3回目のgetSlice()を実行した結果、新しい$stackとして、次の値が得られます.
$stack   = $stack_2;
$pipe    = StartSession::class;
$stack_3 = function ($passable) use ($stack, $pipe) {
        /**
        * @var Middleware $pipe
        */            
    return call_user_func_array([$pipe, 'handle'], [$passable, $stack]);
};

5.4回目のgetSlice()を実行した結果、新しい$stackとして、次の値が得られます.
$stack   = $stack_3;
$pipe    = AddQueuedCookiesToResponse::class;
$stack_4 = function ($passable) use ($stack, $pipe) {
        /**
        * @var Middleware $pipe
        */            
    return call_user_func_array([$pipe, 'handle'], [$passable, $stack]);
};

6.5回目のgetSlice()を実行した結果、新しい$stackとして、次の値が得られます.
$stack   = $stack_4;
$pipe    = CheckForMaintenanceMode::class;
$stack_5 = function ($passable) use ($stack, $pipe) {
        /**
        * @var Middleware $pipe
        */            
    return call_user_func_array([$pipe, 'handle'], [$passable, $stack]);
};

このとき、$stack_5つまりthen()の$runで、call_を実行します.user_func($run,10)は、実行プロセスを参照してください.
1.$stack_5(10) = CheckForMaintenanceMode::handle(10, $stack_4)
echo '10: Check if the application is in the maintenance status.' . PHP_EOL;
stack_4(10);

2.$stack_4(10) = AddQueuedCookiesToResponse::handle(10, $stack_3)
$stack_3(10);
echo '10: Add queued cookies to the response.' . PHP_EOL;

3.$stack_3(10) = StartSession::handle(10, $stack_2)
echo '10: Start session of this request.' . PHP_EOL;
$stack_2(10);
echo '10: Close session of this response.' . PHP_EOL;

4.$stack_2(10) = ShareErrorsFromSession::handle(10, $stack_1)
$stack_1(10);
echo '10: Share the errors variable from response to the views.' . PHP_EOL;

5.$stack_1(10) = VerifyCsrfToken::handle(10, $firstSlice)
echo '10: Verify csrf token when post request.' . PHP_EOL;
$firstSlice(10);

6.$firstSlice(10) =
$firstSlice(10) = call_user_func($destination, 10) = echo '10: Send Request to the Kernel, and Return Response.' . PHP_EOL;

OK、上の実行順を整理します.
1. echo '10: Check if the application is in the maintenance status.' . PHP_EOL; //    step

3_1. echo '10: Start session of this request.' . PHP_EOL; //    step

5. echo '10: Verify csrf token when post request.' . PHP_EOL; //    step

6.echo '10: Send Request to the Kernel, and Return Response.' . PHP_EOL; //   step

4. echo '10: Share the errors variable from response to the views.' . PHP_EOL; //    step

3_2. echo '10: Close session of this response.' . PHP_EOL; //    step

2. echo '10: Add queued cookies to the response.' . PHP_EOL; //    step

上記の一歩一歩の分析を経て、LaravelソースコードのMiddlewareの実行手順が明らかになりました. , , , 。 : Laravel Middleware , , 。 Container , 。
Laravel-Chinaへようこそ.
RightCapital採用Laravel DevOps