pipeline-中間件的實(shí)現(xiàn)

1、 lumen(5.6) 中間件 類型

lumen 中的中間件份為兩種(bootstrap/app.php) :

(1 全局中間件
<?php
 $app->middleware([
     App\Http\Middleware\ExampleMiddleware::class
 ]);
(2 路由中間件 (需分配到route中)
<?php
 $app->routeMiddleware([
     'auth' => App\Http\Middleware\Authenticate::class,
 ]);
保存在 Concerns\RoutesRequests(vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php)
<?php
trait RoutesRequests
{
    /**
     * All of the global middleware for the application.
     *
     * @var array
     */
    protected $middleware = [];

    /**
     * All of the route specific middleware short-hands.
     *
     * @var array
     */
    protected $routeMiddleware = [];
........

2、請(qǐng)求過程

1)入口文件 (public/index.php)
<?php
$app = require __DIR__.'/../bootstrap/app.php';
$app->run();
// 簡單的兩行代碼
2)run()方法 Concerns\RoutesRequests(vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php)
<?php
trait RoutesRequests
{
    ......
    public function run($request = null)
    {
        $response = $this->dispatch($request); // 處理請(qǐng)求 (中間件 等)

        if ($response instanceof SymfonyResponse) {
            $response->send(); // 返回 http 請(qǐng)求結(jié)果
        } else {
            echo (string) $response;
        }
        // 處理 middleware 中的 terminate() -->終止中間件 (有時(shí)候中間件可能需要在 HTTP 響應(yīng)發(fā)送到瀏覽器之后做一些工作)
        if (count($this->middleware) > 0) {
            $this->callTerminableMiddleware($response);
        }
    }
    ......
3) $this->dispatch($request) Concerns\RoutesRequests(vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php)
<?php
trait RoutesRequests
{
    ......
    /**
     * Dispatch the incoming request.
     *
     * @param  SymfonyRequest|null  $request
     * @return Response
     */
    public function dispatch($request = null)
    {
        // 初始化 $request
        list($method, $pathInfo) = $this->parseIncomingRequest($request);

        try {
            // pipeline 處理 全局 中間件 
            return $this->sendThroughPipeline($this->middleware, function () use ($method, $pathInfo) { 
                if (isset($this->router->getRoutes()[$method.$pathInfo])) {
                            // handleFoundRoute() 處理  route中間件 
                    return $this->handleFoundRoute([true, $this->router->getRoutes()[$method.$pathInfo]['action'], []]);
                }
                // 處理 沒有 路由到的 請(qǐng)求404
                return $this->handleDispatcherResponse(
                    $this->createDispatcher()->dispatch($method, $pathInfo)
                );
            });
        } catch (Exception $e) {
            return $this->prepareResponse($this->sendExceptionToHandler($e));
        } catch (Throwable $e) {
            return $this->prepareResponse($this->sendExceptionToHandler($e));
        }
    }
    ......
4) $this->sendThroughPipeline(array $middleware, Closure $then) Concerns\RoutesRequests(vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php)
<?php
trait RoutesRequests
{
    ......
    /**
     * Send the request through the pipeline with the given callback.
     *
     * @param  array  $middleware
     * @param  \Closure  $then
     * @return mixed
     */
    protected function sendThroughPipeline(array $middleware, Closure $then)
    {
        if (count($middleware) > 0 && ! $this->shouldSkipMiddleware()) {
            // pipeline 實(shí)現(xiàn)中間件
            return (new Pipeline($this))
                ->send($this->make('request'))
                ->through($middleware)
                ->then($then);
        }

        return $then();
    }
    ......

3、pipeline 的實(shí)現(xiàn)過程

通過簡單例子

<?php
namespace App\Http\Controllers;
use Illuminate\Pipeline\Pipeline;

class TestController extends Controller{
    function test(){
        $pipes = [
            function ($poster, $callback) {
                $poster += 1;
                return $callback($poster);
            },
            function ($poster, $callback) {
                $result = $callback($poster);

                return $result - 1;
            },
            function ($poster, $callback) {
                $poster += 2;

                return $callback($poster);
            }
        ];

        echo (new Pipeline())->send(0)->through($pipes)->then(function ($poster) {
            return $poster;
        }); // 執(zhí)行輸出為 2
    }
}

->send($passable) 設(shè)置通過管道的對(duì)象

->through($pipes) 設(shè)置管道

->then($closure) 執(zhí)行$closure 并使對(duì)象通過管道

Pipeline 中then()源碼 重點(diǎn)在這個(gè)方法里面 (vendor/illuminate/pipeline/Pipeline.php)
<?php
    ......
    /**
     * Run the pipeline with a final destination callback.
     *
     * @param  \Closure  $destination
     * @return mixed
     */
        public function then(Closure $destination)
    {
        $pipeline = array_reduce(
            array_reverse($this->pipes), $this->carry(), $this->prepareDestination($destination)
        );

        return $pipeline($this->passable);
    }
    ......

    /**
     * Get the final piece of the Closure onion.
     *
     * @param  \Closure  $destination
     * @return \Closure
     */
    protected function prepareDestination(Closure $destination)
    {
        return function ($passable) use ($destination) {
            return $destination($passable);
        };
    }
    ......

     /**
     * Get a Closure that represents a slice of the application onion.
     *
     * @return \Closure
     */
    protected function carry()
    {
        return function ($stack, $pipe) {
            return function ($passable) use ($stack, $pipe) {
                if (is_callable($pipe)) {
                    // 如果管道是閉包的實(shí)例,我們將直接調(diào)用它,
                    // 但否則,我們將解決容器中的管道,并用適當(dāng)?shù)姆椒ê蛥?shù)調(diào)用它,將結(jié)果返回。
                    return $pipe($passable, $stack);
                } elseif (! is_object($pipe)) {
                    list($name, $parameters) = $this->parsePipeString($pipe);

                    // 如果管道是字符串,我們將解析字符串并解析依賴注入容器中的類。
                    // 然后,我們可以構(gòu)建一個(gè)可調(diào)用的函數(shù)并執(zhí)行管道函數(shù),以提供所需的參數(shù)。
                    $pipe = $this->getContainer()->make($name);

                    $parameters = array_merge([$passable, $stack], $parameters);
                } else {
                    // 如果管道已經(jīng)是一個(gè)對(duì)象,我們只做一個(gè)可調(diào)用的,并將它傳遞給管道。
                    // 沒有必要進(jìn)行任何額外的解析和格式化,因?yàn)槲覀兯o出的對(duì)象已經(jīng)是一個(gè)完全實(shí)例化的對(duì)象。
                    $parameters = [$passable, $stack];
                }

                return method_exists($pipe, $this->method)  // $this->method = 'handle';
                                ? $pipe->{$this->method}(...$parameters)
                                : $pipe(...$parameters);
            };
        };
    }
    ......
簡化 示例中的方法
<?php
$pipes = [$pipe1, $pipe2, $pipe3];

$passable = 0;

$destination = $closure4 = function ($poster) {
                            return $poster;
                        };

// 重點(diǎn) array_reduce 方法 ->用回調(diào)函數(shù)迭代地將數(shù)組簡化為單一的值
$pipeline = array_reduce([$pipe3, $pipe2, $pipe1], $closure, $closure5);

$closure5 = function ($passable) use ($destination) {
            return $destination($passable);
        }

$closure = function ($stack, $pipe) {
            return function ($passable) use ($stack, $pipe) {
                ......
            };
        };

array_reduce、pipeline 執(zhí)行過程

pipeline執(zhí)行過程.png

說明: 例子中的pipe使用的是閉包而 lumen中使用的是 calss 或者是 sting=>class 所以在carry()方法里面的 對(duì)應(yīng)得是 if 后面的兩種情況 $poser 相當(dāng)于在lumen 中的$request ;$poster += 1; 和 $poster += 2; 就是件前操作 而 $result - 1; 就是件后操作了。最后 在$destination閉包中去處理 action 操作 ?。?/p>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 簡介 Laravel 中間件提供了一種方便的機(jī)制來過濾進(jìn)入應(yīng)用的 HTTP 請(qǐng)求, 如ValidatePostSi...
    godruoyi閱讀 936評(píng)論 0 6
  • 原文鏈接 必備品 文檔:Documentation API:API Reference 視頻:Laracasts ...
    layjoy閱讀 8,712評(píng)論 0 121
  • Awesome PHP 一個(gè)PHP資源列表,內(nèi)容包括:庫、框架、模板、安全、代碼分析、日志、第三方庫、配置工具、W...
    guanguans閱讀 6,129評(píng)論 0 47
  • 這是一份事后的總結(jié)。在經(jīng)歷了調(diào)優(yōu)過程踩的很多坑之后,我們最終完善并實(shí)施了初步的性能測試方案,通過真實(shí)的測試數(shù)據(jù)歸納...
    胖福哥閱讀 7,177評(píng)論 1 48
  • Composer Repositories Composer源 Firegento - Magento模塊Comp...
    零一間閱讀 4,021評(píng)論 1 66

友情鏈接更多精彩內(nèi)容