webman中间件调用原理示例

sunwenzheng
// 定义事先的中间件
$middlewares = [
    function ($request1, $next) {
        echo "Middleware 1 start\n";
        $request = $next($request1 );
        echo "Middleware 1 end\n";
        return $request;
    },
    function ($request2, $next) {
        echo "Middleware 2 start\n";
        $request = $next($request2  . " c ");
        echo "Middleware 2 end\n";
        return $request;
    },
];

//
$middlewares = array_reverse($middlewares );

//
$callback = array_reduce($middlewares, function ($carry, $pipe) {
    return function ($request) use ($carry, $pipe) {
        return $pipe($request, $carry);
    };
}, function ($request) {
    echo "Processing request: $request\n";
    return $request;
});

// 
$callback("my request");

对应框架代码
https://github.com/walkor/webman-framework/blob/97d8f4cb20e6a862ed1e0d4a236e5234f7aed0c0/src/Middleware.php#L70

https://github.com/walkor/webman-framework/blob/97d8f4cb20e6a862ed1e0d4a236e5234f7aed0c0/src/App.php#L338

https://github.com/walkor/webman-framework/blob/97d8f4cb20e6a862ed1e0d4a236e5234f7aed0c0/src/App.php#L168

825 1 2
1个评论

Tinywan

不错

  • 暂无评论

sunwenzheng

960
积分
0
获赞数
0
粉丝数
2022-08-02 加入
×
🔝