php简单实现中间件功能

中间件顾名思义是指在请求和响应中间,进行请求数据的拦截处理,数据校验,并且进行逻辑处理后判断是否允许进入下一个中间件。中间件分为前缀中间件,后置中间件。可以用于权限认证。日志记录等

下面用面向对象来简单实现一个php中间件功能

1.主程序编写

throughMiddleware($handler, $this->middlewares);
        return $run($request);
    }   

    /**
     * 通过中间件 through the middleware
     * @param $handler
     * @param $stack
     * @return \Closure|mixed
     */
    protected function throughMiddleware($handler, $stack) {
        // 闭包实现中间件功能 closures implement middleware functions
        foreach (array_reverse($stack) as $key => $middleware) {
            $handler = function ($request) use ($handler, $middleware) {
                if ($middleware instanceof \Closure) {
                    return call_user_func($middleware, $request, $handler);
                } else {
                    return call_user_func([new $middleware, 'handle'], $request, $handler);
                }
            };
        }
        return $handler;
    }

    /**
     * 设置中间件 set middleware
     * @param array $middlewares
     */
    public function middleware(array $middlewares) {
        $this->middlewares = $middlewares;
    }
}

2.中间件编写

3.执行代码

middleware([
    Filter::class,
    Auth::class,
    Log::class,
    Format::class,
]);
$request = 1;
$app->run($request);

你可能感兴趣的:(php,中间件,php,java)