中间件顾名思义是指在请求和响应中间,进行请求数据的拦截处理,数据校验,并且进行逻辑处理后判断是否允许进入下一个中间件。中间件分为前缀中间件,后置中间件。可以用于权限认证。日志记录等
下面用面向对象来简单实现一个php中间件功能
1.主程序编写
<?php
class App
{
protected $middlewares = [];
public function run($request) {
$handler = function($request) {
echo $request . " app run\r\n";
};
// 通过中间件
$run = $this->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.中间件编写
<?php
// 前置过滤中间件
class Filter
{
public function handle($request, \Closure $next)
{
$request++;
echo $request . " through filter\r\n";
return $next($request);
}
}
// 前置校验中间件
class Auth
{
public function handle($request, \Closure $next)
{
$request++;
echo $request . " through auth\r\n";
return $next($request);
}
}
// 后置日志中间件
class Log
{
public function handle($request, \Closure $next)
{
$return = $next($request);
echo $request . " through log\r\n";
return $return;
}
}
// 后置格式化中间件
class Format
{
public function handle($request, \Closure $next)
{
$return = $next($request);
echo $request . " through format\r\n";
return $return;
}
}
3.执行代码
<?php
$app = new App();
$app->middleware([
Filter::class,
Auth::class,
Log::class,
Format::class,
]);
$request = 1;
$app->run($request);
|