袁来如此的工作笔记
袁来如此的工作笔记
竹杖芒鞋轻胜马,谁怕? 一蓑烟雨任平生。

PHP框架中间件简单实现

浏览量:118

$db = function ($request, Closure $next) {
    echo '成功建立数据库连接' . PHP_EOL;
    $response = $next($request);
    echo '成功关闭数据库连接' . PHP_EOL;
 
    return $response;
};
 
$like = function ($request, Closure $next) {
    echo '点赞+1' . PHP_EOL;
    $response = $next($request);
    echo '点赞+2' . PHP_EOL;
 
    return $response;
};
 
$app = function ($request) {
    echo $request . PHP_EOL;
    return '一个无聊的返回值';
};
 
$allMiddleware = [$like, $db];
$next = $app;
foreach ($allMiddleware as $middleware) {
    $next = function ($request) use ($middleware, $next) {
        return $middleware($request, $next);
    };
}
 
$response = $next('O(∩_∩)O');
echo $response;
打赏