0%

array_reduce实现路由中间件

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
<?php
interface Middleware
{
public static function handle(Closure $next);
}

class Middleware1 implements Middleware
{
public static function handle(Closure $next)
{
echo "Middleware1 before\n";
$next();
echo "Middleware1 after\n";
}
}

class Middleware2 implements Middleware
{
public static function handle(Closure $next)
{
echo "Middleware2 before\n";
$next();
echo "Middleware2 after\n";
}
}

class Middleware3 implements Middleware
{
public static function handle(Closure $next)
{
echo "Middleware3 before\n";
$next();
echo "Middleware3 after\n";
}
}

function getSlice() // 返回一个函数,与上文的f一致
{
return function ($stack, $pipe) {
return function () use ($stack, $pipe) {
return $pipe::handle($stack);
};
};
}

function then()
{
$pipes = [
"Middleware1",
"Middleware2",
"Middleware3",
];

$firstSlice = function () { // 上文的目标函数 target
echo "请求向路由器传递,返回响应.\n";
};
//嵌套闭包的解包方式是先从外到内,然后从内回归到外面,所以要根据注册顺序进行逆序
$pipes = array_reverse($pipes);
$closure = array_reduce($pipes, getSlice(), $firstSlice);
var_dump($closure);//打印下该闭包
// 因为最终返回了一个函数,所以需要call_user_func
call_user_func(array_reduce($pipes, getSlice(), $firstSlice));
}
then();
echo "\n";
//array_reduce($pipes, getSlice(), $firstSlice),执行完成后相当于生成了f嵌套闭包
//function f()
//{
// return Middleware1::handle(
// function () {
// return Middleware2::handle(
// function () {
// return Middleware3::handle(function () {
// echo "请求向路由器传递,返回响应.\n";
// });
// }
// );
// }
// );
//}
//call_user_func('f');