laravel pipeline 理解

laravel pipeline 理解

代码

简版源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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);
};
};
}
}

测试代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class ALogic
{
public static function handle($data, $next)
{
print "开始 A 逻辑";
$ret = $next($data);
print "结束 A 逻辑";
return $ret;
}
}

class BLogic
{
public static function handle($data, $next)
{
print "开始 B 逻辑";
$ret = $next($data);
print "结束 B 逻辑";
return $ret;
}
}

class CLogic
{
public static function handle($data, $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;
});

输出

  1. 开始 A 逻辑
  2. 开始 B 逻辑
  3. 开始 C 逻辑
  4. any things
  5. 结束 C 逻辑
  6. 结束 B 逻辑
  7. 结束 A 逻辑

理解

核心函数

array_reduce

解析

1
$pipeline($this->passable)
  1. 执行最后一个闭包 传入参数 $pipe ALogic $stack 上一个闭包就是包含 BLogic 打印 “开始 A 逻辑”
  2. 第二个闭包 $pipe BLogic $stack 上一个闭包就是包含 CLogic 打印 “开始 B 逻辑”
  3. 最后一个闭包 $pipe CLogic $stack 上一个闭包就是初始化的闭包 $destination 打印 “开始 C 逻辑”
  4. 执行 $destination 打印 “any things”
  5. CLogic 返回结果 $ret 打印 “结束 C 逻辑”
  6. BLogic 返回结果 $ret 打印 “结束 B 逻辑”
  7. ALogic 返回结果 $ret 打印 “结束 A 逻辑