下面由laravel教程欄目給大家解讀Laravel Pipeline,希望對需要的朋友有所幫助!
大家好,今天給大家介紹下Laravel框架的Pipeline。
它是一個(gè)非常好用的組件,能夠使代碼的結(jié)構(gòu)非常清晰。 Laravel的中間件機(jī)制便是基于它來實(shí)現(xiàn)的。
通過Pipeline,可以輕松實(shí)現(xiàn)APO編程。
官方GIT地址
https://github.com/illuminate/pipeline
下面的代碼是我實(shí)現(xiàn)的一個(gè)簡化版本:
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,生成一個(gè)接受一個(gè)參數(shù)的匿名函數(shù),然后執(zhí)行調(diào)用。
簡單使用示例
class ALogic { public static function handle($data, Clourse $next) { print "開始 A 邏輯"; $ret = $next($data); print "結(jié)束 A 邏輯"; return $ret; } } class BLogic { public static function handle($data, Clourse $next) { print "開始 B 邏輯"; $ret = $next($data); print "結(jié)束 B 邏輯"; return $ret; } } class CLogic { public static function handle($data, Clourse $next) { print "開始 C 邏輯"; $ret = $next($data); print "結(jié)束 C 邏輯"; return $ret; } }
$pipes = [ ALogic::class, BLogic::class, CLogic::class ]; $data = "any things"; (new Pipeline())->send($data)->through($pipes)->then(function($data){ print $data;});
運(yùn)行結(jié)果:
"開始 A 邏輯" "開始 B 邏輯" "開始 C 邏輯" "any things" "結(jié)束 C 邏輯" "結(jié)束 B 邏輯" "結(jié)束 A 邏輯"
AOP示例
AOP 的優(yōu)點(diǎn)就在于動態(tài)的添加功能,而不對其它層次產(chǎn)生影響,可以非常方便的添加或者刪除功能。
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 可以執(zhí)行初始化狀態(tài)的操作 $ret = $next($data) // exec 可以執(zhí)行保存狀態(tài)信息的操作 return $ret; } } $pipes = [ IpCheck::class, StatusManage::class, ]; (new Pipeline())->send($data)->through($pipes)->then(function($data){ "執(zhí)行其它邏輯";});