加载中间件,注册回调事件。
参考Larveal中间件加载方式
具体代码如下:
define("MALE",1);
define("FEMALE",0);
$request = new stdClass();
$request->age = 9;
$request->sex = MALE;
$request->name = "小明";
$request->info = "牛逼的人";
//handle1,2,3,4是我要加入的注册事件,$request是原有请求
function handle1(Closure $next){
return function($request)use($next){
if($request->age<10){
echo "年龄小于10岁,不许坐车。",PHP_EOL;
}
return $next($request);
};
}
function handle2(Closure $next){
return function($request)use($next){
return $next($request);
};
}
function handle3(Closure $next){
return function($request)use($next){
return $next($request);
};
}
function handle4(Closure $next){
return function($request)use($next){
return $next($request);
};
}
function lastClosure(){
return function($request){
var_dump($request);
};
}
//$p2 = call_user_func("handle1",lastClosure());
//$p3 = call_user_func('handle2',$p2);
//$p4= call_user_func('handle3',$p3);
//$p5= call_user_func('handle4',$p4);
//call_user_func($p5,$request);
//die();
$newPipe = new Pipe();
Pipe::register("handle1");
Pipe::register("handle2");
Pipe::register("handle3");
Pipe::register("handle4");
$newPipe->run($request);
class Pipe{
private static $pipes;
public function __construct(){
self::$pipes = array();
}
public static function register($handle){
self::$pipes[] = $handle;
}
//相当于 lastClosure()
public function getFirstClosure(){
return function($request){
var_dump($request);
};
}
public function getClosure(){
return function($closure,$pipe){
return function($request)use($closure,$pipe){
call_user_func(call_user_func($pipe,$closure),$request);
};
};
}
public function run($request){
$firstClosure = $this->getFirstClosure();
/**
* 解释一下:
* array_reduce(self::$pipes,$this->getClosure(),$firstClosure) 中间这个$this->getClosure()肯定是一个双重的closure.调用之后返回的还是一个Closure.
*/
call_user_func(array_reduce(self::$pipes,$this->getClosure(),$firstClosure),$request);
}
}