您现在的位置是:网站首页> 编程资料编程资料
Laravel Reponse响应客户端示例详解_php实例_
2023-05-25
403人已围观
简介 Laravel Reponse响应客户端示例详解_php实例_
前言
本篇文章逻辑较长,只说明和响应生命周期相关的必要代码。
本文主要内容顺序为:
1、执行上文管道中的then方法指定的闭包,路由的分发
2、在路由器中(Router类)找到请求($request 也就是经过全局中间件处理的请求)匹配的路由规则
3、说明路由规则的加载(会跳转到框架的boot过程),注意这部分是在处理请求之前完成的,因为一旦当我们开始处理请求,就意味着所有的路由都应该已经加载好了,供我们的请求进行匹配
4、执行请求匹配到的路由逻辑
5、生成响应,并发送给客户端
6、最后生命周期的结束
7、基本响应类的使用
前文说道,如果一个请求顺利通过了全局中间件那么就会调用管道then方法中传入的闭包
protected function sendRequestThroughRouter($request) { $this->app->instance('request', $request); Facade::clearResolvedInstance('request'); $this->bootstrap(); // 代码如下 return (new Pipeline($this->app)) ->send($request) ->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware) // 此方法将当前请求挂载到容器,然后执行路由器的分发 ->then($this->dispatchToRouter()); } protected function dispatchToRouter() { return function ($request) { $this->app->instance('request', $request); return $this->router->dispatch($request); }; } 查看Illuminate\Routing\Router::dispatch方法
public function dispatch(Request $request) { $this->currentRequest = $request; // 将请求分发到路由 // 跳转到dispatchToRoute方法 return $this->dispatchToRoute($request); } public function dispatchToRoute(Request $request) { // 先跳转到findRoute方法 return $this->runRoute($request, $this->findRoute($request)); } // 见名之意 通过给定的$request 找到匹配的路由 protected function findRoute($request) { // 跳转到Illuminate\Routing\RouteCollection::match方法 $this->current = $route = $this->routes->match($request); $this->container->instance(Route::class, $route); return $route; } 查看Illuminate\Routing\RouteCollection::match方法
/** * Find the first route matching a given request. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Routing\Route * * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException */ public function match(Request $request) { // 根据请求动作找到全局匹配的路由 // 可以自行打印下$routes $routes = $this->get($request->getMethod()); // 匹配路由 下面查看框架如何生成的路由规则!!! $route = $this->matchAgainstRoutes($routes, $request); if (! is_null($route)) { return $route->bind($request); } $others = $this->checkForAlternateVerbs($request); if (count($others) > 0) { return $this->getRouteForMethods($request, $others); } throw new NotFoundHttpException; } 下面说明框架如何加载的路由规则
Application::boot方法
// 主要逻辑是调用服务提供者的boot方法 array_walk($this->serviceProviders, function ($p) { $this->bootProvider($p); }); App\Providers\RouteServiceProvider::boot方法
public function boot() { // 调用父类Illuminate\Foundation\Support\Providers\RouteServiceProvider的boot方法 parent::boot(); } Illuminate\Foundation\Support\Providers\RouteServiceProvider::boot方法
public function boot() { $this->setRootControllerNamespace(); if ($this->routesAreCached()) { $this->loadCachedRoutes(); } else { // 就看这个loadRoutes方法 $this->loadRoutes(); $this->app->booted(function () { // dd(get_class($this->app['router'])); $this->app['router']->getRoutes()->refreshNameLookups(); $this->app['router']->getRoutes()->refreshActionLookups(); }); } } /** * Load the application routes. * 看注释就知道我们来对了地方 * @return void */ protected function loadRoutes() { // 调用App\Providers\RouteServiceProvider的map方法 if (method_exists($this, 'map')) { $this->app->call([$this, 'map']); } } App\Providers\RouteServiceProvider::map方法
public function map() { // 为了调试方便我注释掉了api路由 // $this->mapApiRoutes(); // 这两个都是加载路由文件 这里查看web.php $this->mapWebRoutes(); } protected function mapWebRoutes() { // 调用Router的__call方法 返回的是RouteRegistrar实例 Route::middleware('web') ->namespace($this->namespace) // 调用RouteRegistrar的namespace方法 触发__call魔术方法 // 依然是挂载属性 可自行打印 // Illuminate\Routing\RouteRegistrar {#239 ▼ // #router: Illuminate\Routing\Router {#34 ▶} // #attributes: array:2 [▼ // "middleware" => array:1 [▼ // 0 => "web" // ] // "namespace" => "App\Http\Controllers" // ] // #passthru: array:7 [▶] // #allowedAttributes: array:7 [▶] // #aliases: array:1 [▶] // } // 调用RouteRegistrar的group方法 ->group(base_path('routes/web.php')); } Router::__call方法
public function __call($method, $parameters) { if (static::hasMacro($method)) { return $this->macroCall($method, $parameters); } if ($method === 'middleware') { // 调用了RouteRegistrar的attribute方法 只是挂载路由属性 return (new RouteRegistrar($this))->attribute($method, is_array($parameters[0]) ? $parameters[0] : $parameters); } return (new RouteRegistrar($this))->attribute($method, $parameters[0]); } Illuminate\Routing\RouteRegistrar::__call方法
public function __call($method, $parameters) { if (in_array($method, $this->passthru)) { // 当使用get post等方法的时候 return $this->registerRoute($method, ...$parameters); } if (in_array($method, $this->allowedAttributes)) { if ($method === 'middleware') { return $this->attribute($method, is_array($parameters[0]) ? $parameters[0] : $parameters); } // dd($method); // namespace return $this->attribute($method, $parameters[0]); } throw new BadMethodCallException(sprintf( 'Method %s::%s does not exist.', static::class, $method )); } Illuminate\Routing\RouteRegistrar::group方法
public function group($callback) { // dd($this->attributes, $callback); // array:2 [▼ // "middleware" => array:1 [▼ // 0 => "web" // ] // "namespace" => "App\Http\Controllers" // ] // "/home/vagrant/code/test1/routes/web.php" // 查看Router的group方法 $this->router->group($this->attributes, $callback); } Router::group方法
public function group(array $attributes, $routes) { $this->updateGroupStack($attributes); // 查看loadRoutes方法 /home/vagrant/code/test1/routes/web.php $this->loadRoutes($routes); array_pop($this->groupStack); } protected function loadRoutes($routes) { if ($routes instanceof Closure) { // 用于闭包嵌套 laravel的路由是可以随意潜逃组合的 $routes($this); } else { // 加载路由文件 /home/vagrant/code/test1/routes/web.php (new RouteFileRegistrar($this))->register($routes); } } Illuminate\Routing\RouteFileRegistrar 文件
protected $router; public function __construct(Router $router) { $this->router = $router; } public function register($routes) { $router = $this->router; // 终于加载到了路由文件 // require("/home/vagrant/code/test1/routes/web.php"); // 看到这里就到了大家熟悉的Route::get()等方法了 // 道友们可能已经有了有趣的想法: 可以在web.php等路由文件中继续require其他文件 // 便可实现不同功能模块的路由管理 require $routes; } 了解了理由加载流程,下面举个简单例子,laravel如何注册一个路由
// web.php中 Route::get('routecontroller', "\App\Http\Controllers\Debug\TestController@index"); // 跳转到Router的get方法 /** * Register a new GET route with the router. * * @param string $uri * @param \Closure|array|string|callable|null $action * @return \Illuminate\Routing\Route */ public function get($uri, $action = null) { // dump($uri, $action); // $uri = routecontroller // $action = \App\Http\Controllers\Debug\TestController@index // 跳转到addRoute方法 return $this->addRoute(['GET', 'HEAD'], $uri, $action); } /** * Add a route to the underlying route collection. * * @param array|string $methods * @param string $uri * @param \Closure|array|string|callable|null $action * @return \Illuminate\Routing\Route */ // ['GET', 'HEAD'], $uri, $action public function addRoute($methods, $uri, $action) { // routes是routecollection实例 // 跳转到createRoute方法 // 跳转到RouteCollection的add方法 return $this->routes->add($this->createRoute($methods, $uri, $action)); } /** * Create a new route instance. * * @param array|string $methods * @param string $uri * @param mixed $action * @return \Illuminate\Routing\Route */ // ['GET', 'HEAD'], $uri, $action protected function createRoute($methods, $uri, $action) { // 跳转到actionReferencesController方法 if ($this->actionReferencesController($action)) { $action = $this->convertToControllerAction($action); // dump($action); // array:2 [▼ // "uses" => "\App\Http\Controllers\Debug\TestController@index" // "controller" => "\App\Http\Controllers\Debug\TestController@index" // ] } // 创建一个对应路由规则的Route实例 并且添加到routes(collection)中 // 返回到上面的addRoute方法 // 请自行查看Route的构造方法 $route = $this->newRoute( // dump($this->prefix); // routecontroller $methods, $this->prefix($uri), $action ); if ($this->hasGroupStack()) { $this->mergeGroupAttributesIntoRoute($route); } $this->addWhereClausesToRoute($route); return $route; } /** * Determine if the action is routing to a controller. * * @param array $action * @return bool */ // 判断是否路由到一个控制器 protected function actionReferencesController($action) { // 在此例子中Route::get方法传递的是一个字符串 if (! $action instanceof Closure) { // 返回true return is_string($action) || (isset($action['uses']) && is_string($action['uses'])); } return false; } RouteCollection的add方法
/** * Add a Route instance to the collection. * * @param \Illuminate\Routing\Route $route * @return \Illuminate\Routing\Route */ public function add(Route $route) { // 跳转吧 $this->addToCollections($route); $this->addLookups($route); // 最终一路返回到Router的get方法 所以我们可以直接打印web.php定义的路由规则 return $route; } /** * Add the given route to the arrays of routes. * * @param \Illuminate\Routing\Route $route * @return void */ protected function addToCollections($route) { $domainAndUri = $route->getDomain().$route->uri(); // dump($route->getDomain(), $route->uri()); null routecontroller foreach ($route->methods() as $method) { // 将路由规则挂载到数组 方便匹配 $this->routes[$method][$domainAndUri] = $route; } // 将路由规则挂载的数组 方便匹配 $this->allRoutes[$method.$domainAndUri] = $route; } 至此就生成了一条路由 注意我这里将注册api路由进行了注释,并且保证web.php中只有一条路由
相关内容
- PHP 实现base64编码文件上传出现问题详解_php技巧_
- PHP copy函数使用案例代码解析_php技巧_
- PHP超全局变量实现原理及代码解析_php技巧_
- PHP终止脚本运行三种实现方法详解_php技巧_
- PHP如何使用array_unshift()在数组开头插入元素_php技巧_
- PHP数组Key强制类型转换实现原理解析_php技巧_
- Laravel中GraphQL接口请求频率实战记录_php实例_
- PHP实现Snowflake生成分布式唯一ID的方法示例_php技巧_
- Yii实现微信公众号场景二维码的方法实例_php实例_
- Swoole源码中如何查询Websocket的连接问题详解_php实例_
