你們好,今天給你們介紹下Laravel框架的Pipeline。
它是一個很是好用的組件,可以使代碼的結構很是清晰。 Laravel的中間件機制即是基於它來實現的。php
經過Pipeline,能夠輕鬆實現APO編程。git
https://github.com/illuminate...github
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 的優勢就在於動態的添加功能,而不對其它層次產生影響,能夠很是方便的添加或者刪除功能。app
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){ "執行其它邏輯";});