最近學習PHP,看到了一段代碼,其中涉及到了匿名函數(shù)以及array_reduce,把代碼敲出來用各種方法分析也沒想出是怎么調(diào)用的,代碼如下:
<?php
interface Middleware
{
public static function handle(Closure $next);
}
class VerifyCsrfToken implements Middleware
{
public static function handle(Closure $next)
{
echo "(5)驗證Csrf-Token".'<br>';
$next();
}
}
class ShareErrorsFromSession implements Middleware
{
public static function handle(Closure $next)
{
echo "(4)如果session中有'errors'變量,則共享它".'<br>';
$next();
}
}
class StartSession implements Middleware
{
public static function handle(Closure $next)
{
echo "(3)開啟session,獲取數(shù)據(jù)".'<br>';
$next();
echo "(7)保存數(shù)據(jù),關閉session".'<br>';
}
}
class AddQueuedCookiesToResponse implements Middleware
{
public static function handle(Closure $next)
{
$next();
echo "(8)添加下一次請求需要的cookie".'<br>';
}
}
class EncryptCookies implements Middleware
{
public static function handle(Closure $next)
{
echo "(2)對輸入請求的cookie進行解密".'<br>';
$next();
echo "(9)對輸出相應的cookie進行加密".'<br>';
}
}
class CheckForMaintenanceMode implements Middleware
{
public static function handle(Closure $next)
{
echo "(1)確定當前程序是否處于維護狀態(tài)".'<br>';
$next();
}
}
function getSlice()
{
return function($stack, $pipe)
{
return function() use ($stack, $pipe)
{
return $pipe::handle($stack);
};
};
}
function then()
{
$pipes = [
"CheckForMaintenanceMode",
"EncryptCookies",
"AddQueuedCookiesToResponse",
"StartSession",
"ShareErrorsFromSession",
"VerifyCsrfToken"
];
$firstSlice = function() {
echo "(6)請求向路由器傳遞,返回響應.".'<br>';
};
$pipes = array_reverse($pipes);
$go = array_reduce($pipes, getSlice(),$firstSlice);
$go();
}
then();
?>
還望有大神能幫忙詳解下$go = array_reduce($pipes, getSlice(),$firstSlice);和$go();這兩段代碼背后的每一步的調(diào)用執(zhí)行流程,以及調(diào)用時的參數(shù)傳遞是哪些,如果能用流程圖表示就更好啦,謝謝。
添加回答
舉報
0/150
提交
取消