首先我需要介绍下php的 array_reduce 函数。
mixed array_reduce ( array $array , callable $callback [, mixed $initial = NULL ] )
参数说明:
- $array:需要处理的数组
- $callback:回调函数,用于对数组元素进行操作的函数。该函数接受两个参数,第一个参数是上一次操作的结果,第二个参数是当前数组元素的值
- $initial:可选参数,作为回调函数的第一个参数传递给回调函数的初始值
$array = [1, 2, 3, 4, 5];
$result = array_reduce($array, function($carry, $item) {
return $carry + $item;
}, 0);
echo $result; // 输出:15
在上面的示例中,array_reduce函数对数组中的元素进行累加操作,初始值为0,最终返回数组元素的和。
好了,上PHP的中间件的原理代码。
<?php
// https://zhuanlan.zhihu.com/p/331739637
$step1 = function ($next){
echo "第一步中间件".PHP_EOL;
$next();
};
$step2=function ($next){
echo "第二步中间件".PHP_EOL;
$next();
};
$step3 = function ($next){
echo "第三步中间件".PHP_EOL;
$next();
};
$sucess = function (){
echo "最后中间件".PHP_EOL;
};
$callback = function ($next,$step) {
return function () use ( $next, $step ) {
return $step($next);
};
};
$middleWares = [
$step1,
$step2,
$step3
];
$middleWares=array_reverse($middleWares); //将数组元素顺序反转
call_user_func(
//必需。规定数组。
//必需。规定函数的名称。
//规定发送到函数处理的第一个值。
array_reduce($middleWares,$callback,$sucess)
);
<?php
$step1 = function ($next){
echo "第一步中间件".PHP_EOL;
$next();
};
$step2=function ($next){
echo "第二步中间件".PHP_EOL;
$next();
};
$step3 = function ($next){
echo "第三步中间件".PHP_EOL;
$next();
};
$sucess = function (){
echo "最后中间件".PHP_EOL;
};
$callback = function ($next,$step) {
return function () use ( $next, $step ) {
return $step($next);
};
};
//先执行step1 再step2 再step3 最后$sucess
$middleWares = [
$step1,
$step2,
$step3,
$sucess
];
$demo=function () use($step3, $sucess){
$step3($sucess);
echo "demo";
};
$demo2=function () use($step2, $demo){
$step2($demo);
echo "demo2";
};
// $demo2();
$demo2=function () use($step2, $demo){
$step2($demo);
echo "demo2";
};
$demo2();
//
// call_user_func(
// $demo
// );
认真阅读下这些代码哦。。就是PHP的闭包回调,闭包回调,闭包回调,闭包回调。。