1
<?php
//应用层
$handler = function($name) {
    $name ++;
    echo "{$name} application<br/>";
};
//前置过滤中间件
$filter = function($handler) {
    return function($name) use ($handler) {
        $name ++;
        echo "{$name} filter<br/>";
        return $handler($name);
    };
};
//前置校验中间件
$auth = function($handler) {
    return function($name) use ($handler) {
        $name ++;;
        echo "{$name} auth <br/>";
        return $handler($name);
    };
};
//后置日志中间件
$log = function($handler) {
    return function($name) use ($handler) {
        $return = $handler($name);
        $name ++;
        echo "{$name} log<br/>";
        return $return;
    };
};
//执行中间件
function run($handler, $stack)
{
    foreach (array_reverse($stack) as $key => $middleware) {
        $handler = $middleware($handler);
    }
    return $handler;
}
// 中间件栈
$stack = [];
// 注册中间件
$stack['log'] = $log;
$stack['filter'] = $filter;
$stack['auth'] = $auth;

$run = run($handler, $stack);   //等同于$run = $log($filter($auth($handler)));
$run(1);

如若时光萧瑟去丶
111 声望9 粉丝

weakChickenPeng.