pipeline-中间件的实现

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、请求过程

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); // 处理请求 (中间件 等)

        if ($response instanceof SymfonyResponse) {
            $response->send(); // 返回 http 请求结果
        } else {
            echo (string) $response;
        }
        // 处理 middleware 中的 terminate() -->终止中间件 (有时候中间件可能需要在 HTTP 响应发送到浏览器之后做一些工作)
        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'], []]);
                }
                // 处理 没有 路由到的 请求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 实现中间件
            return (new Pipeline($this))
                ->send($this->make('request'))
                ->through($middleware)
                ->then($then);
        }

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

3、pipeline 的实现过程

通过简单例子

<?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;
        }); // 执行输出为 2
    }
}

->send($passable) 设置通过管道的对象

->through($pipes) 设置管道

->then($closure) 执行$closure 并使对象通过管道

Pipeline 中then()源码 重点在这个方法里面 (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)) {
                    // 如果管道是闭包的实例,我们将直接调用它,
                    // 但否则,我们将解决容器中的管道,并用适当的方法和参数调用它,将结果返回。
                    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 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;
                        };

// 重点 array_reduce 方法 ->用回调函数迭代地将数组简化为单一的值
$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 执行过程

pipeline执行过程.png

说明: 例子中的pipe使用的是闭包而 lumen中使用的是 calss 或者是 sting=>class 所以在carry()方法里面的 对应得是 if 后面的两种情况 $poser 相当于在lumen 中的$request ;$poster += 1; 和 $poster += 2; 就是件前操作 而 $result - 1; 就是件后操作了。最后 在$destination闭包中去处理 action 操作 !!

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,290评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,399评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,021评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,034评论 0 207
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,412评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,651评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,902评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,605评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,339评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,586评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,076评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,400评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,060评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,851评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,685评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,595评论 2 270

推荐阅读更多精彩内容

  • 简介 Laravel 中间件提供了一种方便的机制来过滤进入应用的 HTTP 请求, 如ValidatePostSi...
    godruoyi阅读 901评论 0 6
  • 原文链接 必备品 文档:Documentation API:API Reference 视频:Laracasts ...
    layjoy阅读 8,517评论 0 121
  • Awesome PHP 一个PHP资源列表,内容包括:库、框架、模板、安全、代码分析、日志、第三方库、配置工具、W...
    guanguans阅读 5,685评论 0 47
  • 这是一份事后的总结。在经历了调优过程踩的很多坑之后,我们最终完善并实施了初步的性能测试方案,通过真实的测试数据归纳...
    胖福哥阅读 6,926评论 1 48
  • Composer Repositories Composer源 Firegento - Magento模块Comp...
    零一间阅读 3,940评论 1 66