人人好,本日给人人引见下Laravel框架的Pipeline。
它是一个异常好用的组件,可以使代码的构造异常清楚。 Laravel的中间件机制就是基于它来完成的。
经由过程Pipeline,可以轻松完成APO编程。
官方GIT地点
https://github.com/illuminate...
下面的代码是我完成的一个简化版本:
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的剖析(代码示例)的细致内容,更多请关注ki4网别的相干文章!