Pipeline 设计模式原理
Pipeline 设计模式
若水管过长且存在破损,不仅会漏水,还难以适应复杂环境的弯曲需求。因此,通常将长管分割为短节,根据因地制宜的原则最大化利用不同规格管道,通过组装满足多样化需求。
基于此衍生出 Pipeline 设计模式,即将冗长的复杂流程拆解为独立的小任务。每个最小单元的任务具备可复用性,通过组合不同的小任务,构建出复杂多样的业务流程。
最终将输入数据引入管道,依据每个小任务对数据进行加工或过滤,最后输出符合预期的结果。
可参考 Koa 框架的中间件机制,即俗称的“剥洋葱”处理思路。

在前端领域,早期工程打包工具 gulp 的实现方式更能体现 pipeline 的思想。
gulp.task('css', function(){
return gulp.src('client/templates/*.less')
.pipe(less())
.pipe(minifyCSS())
.pipe(gulp.dest('build/css'))
});
gulp.task('js', function(){
return gulp.src('client/javascript/*.js')
.pipe(sourcemaps.init())
.pipe(concat('app.min.js'))
.pipe(sourcemaps.write())
.pipe(gulp.dest('build/js'))
});
gulp.task('default', [ 'html', 'css', 'js' ]);
IlluminatePipeline
Laravel 框架中的中间件功能正是基于 Illuminate\Pipeline 实现的。鉴于网上已有大量关于 Laravel 中间件源码解读的文章,此处不再赘述,仅简要说明如何使用 Illuminate\Pipeline。
public function demo(Request $request)
{
$pipe1 = function ($payload, Closure $next) {
$payload = $payload + 1;
return $next($payload);
};
$pipe2 = function ($payload, Closure $next) {
$payload = $payload * 3;
return $next($payload);
};
$data = $request->input('data', 0);
$pipeline = new Pipeline();
return $pipeline
->send($data)
->through([$pipe1, $pipe2])
->then(function ($data) {
return $data;
});
}
本次主要学习“Pipeline”概念,并推荐一个 PHP 插件:league/pipeline。
composer require league/pipeline
该插件的使用方式非常便捷。
use League\Pipeline\Pipeline;
class TimesTwoStage
{
public function __invoke($payload)
{
return $payload * 2;
}
}
class AddOneStage
{
public function __invoke($payload)
{
return $payload + 1;
}
}
$pipeline = (new Pipeline)
->pipe(new TimesTwoStage)
->pipe(new AddOneStage);
// Returns 21
$pipeline->process(10);
接下来我们在项目中集成 FastRouter 以便进行测试。

将上述代码修改如下。

随后观察 RespondJson 内部的具体实现逻辑。
<?php
namespace Platapps\Middlewares;
class RespondJson
{
public function __invoke($payload)
{
header('Content-type:text/json');
return $payload;
}
}
仅仅增加了一个 header 配置。
尝试注释掉其中一个管道阶段。

再次访问时,输出结果变为。

这仅是简单的中间件示例,实际场景远不止于此。此处展示核心代码,完整实现较为简单,可查阅相关文档。
我们需要最终修改 pipe 方法。
namespace League\Pipeline;
class Pipeline implements PipelineInterface
{
/**
* @var callable[]
*/
private $stages = [];
/**
* @var ProcessorInterface
*/
private $processor;
public function __construct(ProcessorInterface $processor = null, callable ...$stages)
{
$this->processor = $processor ?? new FingersCrossedProcessor;
$this->stages = $stages;
}
public function pipe(callable $stage): PipelineInterface
{
$pipeline = clone $this;
$pipeline->stages[] = $stage;
return $pipeline;
}
public function process($payload)
{
return $this->processor->process($payload, ...$this->stages);
}
public function __invoke($payload)
{
return $this->process($payload);
}
}
在众多框架中,建议参考 Tp6 的实现,其功能已足够完善。
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: yunwuxin <448901948@qq.com>
// +----------------------------------------------------------------------
namespace think;
use Closure;
use Exception;
use Throwable;
class Pipeline
{
protected $passable;
protected $pipes = [];
protected $exceptionHandler;
/**
* 初始数据
* @param $passable
* @return $this
*/
public function send($passable)
{
$this->passable = $passable;
return $this;
}
/**
* 调用栈
* @param $pipes
* @return $this
*/
public function through($pipes)
{
$this->pipes = is_array($pipes) ? $pipes : func_get_args();
return $this;
}
/**
* 执行
* @param Closure $destination
* @return mixed
*/
public function then(Closure $destination)
{
$pipeline = array_reduce(
array_reverse($this->pipes),
$this->carry(),
function ($passable) use ($destination) {
try {
return $destination($passable);
} catch (Throwable | Exception $e) {
return $this->handleException($passable, $e);
}
});
return $pipeline($this->passable);
}
/**
* 设置异常处理器
* @param callable $handler
* @return $this
*/
public function whenException($handler)
{
$this->exceptionHandler = $handler;
return $this;
}
protected function carry()
{
return function ($stack, $pipe) {
return function ($passable) use ($stack, $pipe) {
try {
return $pipe($passable, $stack);
} catch (Throwable | Exception $e) {
return $this->handleException($passable, $e);
}
};
};
}
/**
* 异常处理
* @param $passable
* @param $e
* @return mixed
*/
protected function handleException($passable, Throwable $e)
{
if ($this->exceptionHandler) {
return call_user_func($this->exceptionHandler, $passable, $e);
}
throw $e;
}
}
这种写法的优势何在?
优势在于请求处理过程中,各中间件只需关注自身负责的处理逻辑、输入及输出。当数据抵达 Controller 时,业务逻辑的处理能力得到增强。
到此这篇关于PHP Pipeline 实现中间件的示例代码的文章就介绍到这了,更多相关PHP Pipeline 中间件内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!