那个网站ppt做的比较好,网站建设优化解析,网络规划设计师教程第二版,网站设计分享众所周知php框架的中间件核心是通过array_reduce实现的 php之框架中间件模式开发实现、array_reduce的应用 1.先写个测试用例看一下函数的特性2.根据执行特性实现中间件 1.先写个测试用例看一下函数的特性
?phpfunction kernal($a,$b){return $a . and .…众所周知php框架的中间件核心是通过array_reduce实现的 php之框架中间件模式开发实现、array_reduce的应用 1.先写个测试用例看一下函数的特性2.根据执行特性实现中间件 1.先写个测试用例看一下函数的特性
?phpfunction kernal($a,$b){return $a . and . $b;}$array [1,2,3];print_r(array_reduce($array, kernal, [Initial])); //[Initial] and 1 and 2 and 3?可以看出来顺序是连贯的 参数传入是 initial,1,2,3 但是他并不是执行了多个auth函数,反而更像是字符串的连接方式 “inital”.“1”.“2”.3把结果连成了一串
2.根据执行特性实现中间件
?php//一次请求方法,next相当于下一个中间件function baseMiddle($request,$next){$request . 前置1;$res $next($request);echo 后置1.\r\n;return $res;}function kernal($next,$handler){return function ($request) use ($handler, $next) {echo 前置01|.$handler.\r\n;$res $handler($request, $next);echo 后置01.$handler.\r\n;return $res;};}function middleClass1($request,$next){$request . 前置2;$res $next($request);echo 后置2.\r\n;return $res;}function middleClass2($request,$next){$request . 前置3;$res $next($request);echo 后置3.\r\n;return $res;}//这是一个存放中间件方法的数组$array [baseMiddle,middleClass1,middleClass2];$handler array_reduce(array_reverse($array), kernal, function($response){ return $response;}); $response $handler(begin);var_dump($response);/**前置01|baseMiddle前置1前置01|middleClass1前置2前置01|middleClass2前置3后置3后置01middleClass2后置2后置01middleClass1后置1后置01baseMiddlestring(26) begin前置1前置2前置3**/
?根据输出结果我们可以看到代码的执行顺序更好的了解array_reduce的特性