美文网首页我爱编程
pipeline-中间件的实现

pipeline-中间件的实现

作者: ling_1992 | 来源:发表于2018-04-12 10:48 被阅读0次

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 操作 !!

相关文章

网友评论

    本文标题:pipeline-中间件的实现

    本文链接:https://www.haomeiwen.com/subject/sikxkftx.html