下面由laravel教程栏目给大家解读laravel pipeline,希望对需要的朋友有所帮助!
laravel pipeline解读大家好,今天给大家介绍下laravel框架的pipeline。
它是一个非常好用的组件,能够使代码的结构非常清晰。 laravel的中间件机制便是基于它来实现的。
通过pipeline,可以轻松实现apo编程。
官方git地址https://github.com/illuminate/pipeline
下面的代码是我实现的一个简化版本:class pipeline{ /** * the method to call on each pipe * @var string */ protected $method = 'handle'; /** * the object being passed throw the pipeline * @var mixed */ protected $passable; /** * the array of class pipes * @var array */ protected $pipes = []; /** * set the object being sent through the pipeline * * @param $passable * @return $this */ public function send($passable) { $this->passable = $passable; return $this; } /** * set the method to call on the pipes * @param array $pipes * @return $this */ public function through($pipes) { $this->pipes = $pipes; return $this; } /** * @param \closure $destination * @return mixed */ public function then(\closure $destination) { $pipeline = array_reduce(array_reverse($this->pipes), $this->getslice(), $destination); return $pipeline($this->passable); } /** * get a closure that represents a slice of the application onion * @return \closure */ protected function getslice() { return function($stack, $pipe){ return function ($request) use ($stack, $pipe) { return $pipe::{$this->method}($request, $stack); }; }; }}
此类主要逻辑就在于then和getslice方法。通过array_reduce,生成一个接受一个参数的匿名函数,然后执行调用。
简单使用示例class alogic{ public static function handle($data, \clourse $next) { print 开始 a 逻辑; $ret = $next($data); print 结束 a 逻辑; return $ret; }}class blogic{ public static function handle($data, \clourse $next) { print 开始 b 逻辑; $ret = $next($data); print 结束 b 逻辑; return $ret; }}class clogic{ public static function handle($data, \clourse $next) { print 开始 c 逻辑; $ret = $next($data); print 结束 c 逻辑; return $ret; }}
$pipes = [ alogic::class, blogic::class, clogic::class];$data = any things;(new pipeline())->send($data)->through($pipes)->then(function($data){ print $data;});
运行结果:开始 a 逻辑开始 b 逻辑开始 c 逻辑any things结束 c 逻辑结束 b 逻辑结束 a 逻辑
aop示例aop 的优点就在于动态的添加功能,而不对其它层次产生影响,可以非常方便的添加或者删除功能。
class ipcheck{ public static function handle($data, \clourse $next) { if (ip invalid) { // ip 不合法 throw exception(ip invalid); } return $next($data); }}class statusmanage{ public static function handle($data, \clourse $next) { // exec 可以执行初始化状态的操作 $ret = $next($data) // exec 可以执行保存状态信息的操作 return $ret; }}$pipes = [ ipcheck::class, statusmanage::class,];(new pipeline())->send($data)->through($pipes)->then(function($data){ 执行其它逻辑;});
以上就是关于laravel pipeline的解读的详细内容。