Всем привет, сегодня я хотел бы представить вам конвейер фреймворка Laravel. Это очень полезный компонент, который делает структуру кода очень понятной. На этом основан механизм промежуточного программного обеспечения Laravel.
С помощью конвейера можно легко реализовать программирование APO.
Официальный адрес GIT
Официальный адрес GIT
Следующий код является упрощенной версией моей реализации:
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 и get Slice. С помощью array_reduce создается анонимная функция, принимающая параметр, а затем выполняется вызов.
Простой Пример Использования
class ALogic
{
public static function handle($data, \Clourse $next)
{
Print "Start A Logic";
$ret = $next($data);
Print "End A Logic";
return $ret;
}
}
class BLogic
{
public static function handle($data, \Clourse $next)
{
Print "Begin B logic";
$ret = $next($data);
Print "end B logic";
return $ret;
}
}
class CLogic
{
public static function handle($data, \Clourse $next)
{
Print "Start C logic";
$ret = $next($data);
Print "end C logic";
return $ret;
}
}$pipes = [
ALogic::class,
BLogic::class,
CLogic::class
];
$data = "any things";
(new Pipeline())->send($data)->through($pipes)->then(function($data){ print $data;});Результаты операции:
"Begin Logic A" "Begin Logic B" "Start C Logic" "any things" "End C Logic" "End B Logic" "End A Logic"
Пример AOP
Преимущество AOP заключается в том, что он может динамически добавлять или удалять функции, не влияя на другие уровни.
class IpCheck
{
public static function handle($data, \Clourse $next)
{
If ("IP invalid") {// IP is illegal
throw Exception("ip invalid");
}
return $next($data);
}
}
class StatusManage
{
public static function handle($data, \Clourse $next)
{
// exec can perform initialization operation
$ret = $next($data)
// Exc can perform the operation of saving status information
return $ret;
}
}
$pipes = [
IpCheck::class,
StatusManage::class,
];
(new Pipeline () - > send ($data) - > through ($pipes) - > then (function ($data) {"perform other logic";};