1. 程式人生 > >使用回撥的方式實現中介軟體-laravel

使用回撥的方式實現中介軟體-laravel

$app = function ($request) {
    echo $request . "\n";
    return "專案執行中.....";
};

// 現在想在$app中加入一些額外的資訊
$checkToken = function ($request, Closure $next) {
    echo "檢測token中....\n";
    $response = $next($request);
    echo "檢測token完成\n";

    return $response;
};

$checkPermission = function ($request, Closure $next) {
    echo "檢測許可權中....\n";
    $response = $next($request);
    echo "檢測許可權完成\n";
    return $response;
};

$middleware = [
    $checkToken,
    $checkPermission
];

$next = $app;

foreach ($middleware as $m) {
    $next = function ($request) use ($m, $next) {
        return $m($request, $next);
    };
}

$res = $next("haha");

echo $res;