public function handle($request, Closure $next) {
//do something for $request
return $next($request);
}
return (new Pipeline($this->container))
->send($request)
->through($middleware)
->then(function ($request) use ($route) {
return $this->prepareResponse(
$request,
$route->run($request)
);
});
public function send($passable){
$this->passable = $passable;
return $this;
}
public function through($pipes){
$this->pipes = is_array($pipes) ? $pipes : func_get_args();
return $this;
}
public function then(Closure $destination){
//then方法接受一个闭包作为参数,然后经过getInitialSlice包装,而getInitialSlice返回的其实也是一个闭包,如果还不知道什么是闭包先去看PHP文档
$firstSlice = $this->getInitialSlice($destination);
//反转中间件数组,主要是利用了栈的特性,用处接下来再说
$pipes = array_reverse($this->pipes);
//这个call_user_func先不要看,它其实就是执行了一个array_reduce返回的闭包
return call_user_func(
//接下来用array_reduce来用回调函数处理数组,建议先去PHP文档读懂array_reduce的执行原理。其实arrary_reduce什么事情都没干,就是包装闭包然后移交给call_user_func来执行
array_reduce($pipes, $this->getSlice(), $firstSlice), $this->passable
);
}
protected function getSlice(){
return function ($stack, $pipe) { //这里$stack
return function ($passable) use ($stack, $pipe) {
if ($pipe instanceof Closure) {
return call_user_func($pipe, $passable, $stack);
} else {
list($name, $parameters) = $this->parsePipeString($pipe);
return call_user_func_array([$this->container->make($name), $this->method],
array_merge([$passable, $stack], $parameters));
}
};
};
}
//这里的$stack其实就是闭包,第一次遍历的时候会传入$firstSlice这个闭包,以后每次都会传入下面的那个function; 而$pipe就是每一个中间件
array_reduce($pipes, function ($stack, $pipe) {
return function ($passable) use ($stack, $pipe) {
};
}, $firstSlice);
//判断是否为闭包,这里就是判断中间件形式是不是闭包,是的话直接执行并且传入$passable[请求实例]和$stack[传递给下一个中间件的闭包],并且返回
if ($pipe instanceof Closure) {
return call_user_func($pipe, $passable, $stack);
//不是闭包的时候就是形如这样Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode执行
} else {
//解析,把名称返回,这个$parameters看了许久源码还是看不懂,应该是和参数相关,不过不影响我们的分析
list($name, $parameters) = $this->parsePipeString($pipe);
//从容器中解析出中间件实例并且执行handle方法
return call_user_func_array([$this->container->make($name), $this->method],
//$passable就是请求实例,而$stack就是传递的闭包
array_merge([$passable, $stack], $parameters));
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有