-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPipeline.php
129 lines (117 loc) · 2.54 KB
/
Pipeline.php
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
<?php
/**
* 管道设计
*
* 管道就像一个流水线,把复杂的问题的解决方案分解成一个个处理单元,然后依次处理,前一个处理单元的结果就是下一个处理单元的输入。
* Laravel 中的中间件就是利用管道来执行的
*/
class Pipeline
{
/**
* 初始传入的数据
*
* @var mixed
*/
protected $passable;
/**
* 管道集合
*
* @var array
*/
protected $pipes = [];
/**
* 设置管道初始数据
*
* @param mixed $passable 数据
*
* @return Pipeline
*/
public function send($passable): Pipeline
{
$this->passable = $passable;
return $this;
}
/**
* 获取管道初始数据
*
* @return mixed
*/
public function passable()
{
return $this->passable;
}
/**
* 设置管道集合
*
* @param array $pipes 管道集合
*
* @return Pipeline
*/
public function through(array $pipes): Pipeline
{
$this->pipes = $pipes;
return $this;
}
/**
* 获取管道集合
*
* @return array
*/
public function pipes(): array
{
return $this->pipes;
}
/**
* 运行管道
*
* @param Closure $destination 管道最终运行闭包
*
* @return mixed
*/
public function then(Closure $destination)
{
$next = $destination;
$pipes = array_reverse($this->pipes);
foreach ($pipes as $pipe) {
$next = function ($passable) use ($next, $pipe) {
if (is_callable($pipe)) {
return $pipe($passable, $next);
} else {
return (new $pipe)->handle($passable, $next);
}
};
}
return $next($this->passable);
}
}
class PipeTest
{
public function handle($passable, $next)
{
$passable .= '5';
return $next($passable);
}
}
$pipes = [
function ($passable, $next) {
$passable .= '1';
return $next($passable);
},
function ($passable, $next) {
$passable .= '2';
$result = $next($passable);
// 后置管道
$result .= '3';
return $result;
},
function ($passable, $next) {
$passable .= '4';
return $next($passable);
},
PipeTest::class
];
echo (new Pipeline)->send('0')->through($pipes)->then(function ($passable) {
$passable .= '6';
return $passable;
});
// 0124563