Laravel核心解读--路由(Route)

路由是外界访问Laravel应用程序的通路或者说路由定义了Laravel的应用程序向外界提供服务的具体方式:通过指定的URI、HTTP请求方法以及路由参数(可选)才能正确访问到路由定义的处理程序。无论URI对应的处理程序是一个简单的闭包还是说是控制器方法没有对应的路由外界都访问不到他们,今天我们就来看看Laravel是如何来设计和实现路由的。

我们在路由文件里通常是向下面这样来定义路由的:

Route::get('/user', 'UsersController@index');

通过上面的路由我们可以知道,客户端通过以HTTP GET方式来请求 URI "/user"时,Laravel会把请求最终派发给UsersController类的index方法来进行处理,然后在index方法中返回响应给客户端。

上面注册路由时用到的Route类在Laravel里叫门面(Facade),它提供了一种简单的方式来访问绑定到服务容器里的服务router,Facade的设计理念和实现方式我打算以后单开博文来写,在这里我们只要知道调用的Route这个门面的静态方法都对应服务容器里router这个服务的方法,所以上面那条路由你也可以看成是这样来注册的:

app()->make('router')->get('user', 'UsersController@index');

router这个服务是在实例化应用程序Application时在构造方法里通过注册RoutingServiceProvider时绑定到服务容器里的:


 
  1. //bootstrap/app.php
  2. $app = new Illuminate\Foundation\Application(
  3. realpath(__DIR__.'/../')
  4. );
  5.  
  6. //Application: 构造方法
  7. public function __construct($basePath = null)
  8. {
  9. if ($basePath) {
  10. $this->setBasePath($basePath);
  11. }
  12.  
  13. $this->registerBaseBindings();
  14.  
  15. $this->registerBaseServiceProviders();
  16.  
  17. $this->registerCoreContainerAliases();
  18. }
  19.  
  20. //Application: 注册基础的服务提供器
  21. protected function registerBaseServiceProviders()
  22. {
  23. $this->register(new EventServiceProvider($this));
  24.  
  25. $this->register(new LogServiceProvider($this));
  26.  
  27. $this->register(new RoutingServiceProvider($this));
  28. }
  29.  
  30. //\Illuminate\Routing\RoutingServiceProvider: 绑定router到服务容器
  31. protected function registerRouter()
  32. {
  33. $this->app->singleton('router', function ($app) {
  34. return new Router($app['events'], $app);
  35. });
  36. }

通过上面的代码我们知道了Route调用的静态方法都对应于\Illuminate\Routing\Router类里的方法,Router这个类里包含了与路由的注册、寻址、调度相关的方法。

下面我们从路由的注册、加载、寻址这几个阶段来看一下laravel里是如何实现这些的。

路由加载

注册路由前需要先加载路由文件,路由文件的加载是在App\Providers\RouteServiceProvider这个服务器提供者的boot方法里加载的:


 
  1. class RouteServiceProvider extends ServiceProvider
  2. {
  3. public function boot()
  4. {
  5. parent::boot();
  6. }
  7.  
  8. public function map()
  9. {
  10. $this->mapApiRoutes();
  11.  
  12. $this->mapWebRoutes();
  13. }
  14.  
  15. protected function mapWebRoutes()
  16. {
  17. Route::middleware('web')
  18. ->namespace($this->namespace)
  19. ->group(base_path('routes/web.php'));
  20. }
  21.  
  22. protected function mapApiRoutes()
  23. {
  24. Route::prefix('api')
  25. ->middleware('api')
  26. ->namespace($this->namespace)
  27. ->group(base_path('routes/api.php'));
  28. }
  29. }

 
  1. namespace Illuminate\Foundation\Support\Providers;
  2.  
  3. class RouteServiceProvider extends ServiceProvider
  4. {
  5.  
  6. public function boot()
  7. {
  8. $this->setRootControllerNamespace();
  9.  
  10. if ($this->app->routesAreCached()) {
  11. $this->loadCachedRoutes();
  12. } else {
  13. $this->loadRoutes();
  14.  
  15. $this->app->booted(function () {
  16. $this->app['router']->getRoutes()->refreshNameLookups();
  17. $this->app['router']->getRoutes()->refreshActionLookups();
  18. });
  19. }
  20. }
  21.  
  22. protected function loadCachedRoutes()
  23. {
  24. $this->app->booted(function () {
  25. require $this->app->getCachedRoutesPath();
  26. });
  27. }
  28.  
  29. protected function loadRoutes()
  30. {
  31. if (method_exists($this, 'map')) {
  32. $this->app->call([$this, 'map']);
  33. }
  34. }
  35. }
  36.  
  37. class Application extends Container implements ApplicationContract, HttpKernelInterface
  38. {
  39. public function routesAreCached()
  40. {
  41. return $this['files']->exists($this->getCachedRoutesPath());
  42. }
  43.  
  44. public function getCachedRoutesPath()
  45. {
  46. return $this->bootstrapPath().'/cache/routes.php';
  47. }
  48. }

laravel 首先去寻找路由的缓存文件,没有缓存文件再去进行加载路由。缓存文件一般在 bootstrap/cache/routes.php 文件中。
方法loadRoutes会调用map方法来加载路由文件里的路由,map这个函数在App\Providers\RouteServiceProvider类中,这个类继承自Illuminate\Foundation\Support\Providers\RouteServiceProvider。通过map方法我们能看到laravel将路由分为两个大组:api、web。这两个部分的路由分别写在两个文件中:routes/web.php、routes/api.php。

Laravel5.5里是把路由分别放在了几个文件里,之前的版本是在app/Http/routes.php文件里。放在多个文件里能更方便地管理API路由和与WEB路由

路由注册

我们通常都是用Route这个Facade调用静态方法get, post, head, options, put, patch, delete......等来注册路由,上面我们也说了这些静态方法其实是调用了Router类里的方法:


 
  1. public function get($uri, $action = null)
  2. {
  3. return $this->addRoute(['GET', 'HEAD'], $uri, $action);
  4. }
  5.  
  6. public function post($uri, $action = null)
  7. {
  8. return $this->addRoute('POST', $uri, $action);
  9. }
  10. ....

可以看到路由的注册统一都是由router类的addRoute方法来处理的:


 
  1. //注册路由到RouteCollection
  2. protected function addRoute($methods, $uri, $action)
  3. {
  4. return $this->routes->add($this->createRoute($methods, $uri, $action));
  5. }
  6.  
  7. //创建路由
  8. protected function createRoute($methods, $uri, $action)
  9. {
  10. if ($this->actionReferencesController($action)) {
  11. //controller@action类型的路由在这里要进行转换
  12. $action = $this->convertToControllerAction($action);
  13. }
  14.  
  15. $route = $this->newRoute(
  16. $methods, $this->prefix($uri), $action
  17. );
  18.  
  19. if ($this->hasGroupStack()) {
  20. $this->mergeGroupAttributesIntoRoute($route);
  21. }
  22.  
  23. $this->addWhereClausesToRoute($route);
  24.  
  25. return $route;
  26. }
  27.  
  28. protected function convertToControllerAction($action)
  29. {
  30. if (is_string($action)) {
  31. $action = ['uses' => $action];
  32. }
  33.  
  34. if (! empty($this->groupStack)) {
  35. $action['uses'] = $this->prependGroupNamespace($action['uses']);
  36. }
  37.  
  38. $action['controller'] = $action['uses'];
  39.  
  40. return $action;
  41. }

注册路由时传递给addRoute的第三个参数action可以闭包、字符串或者数组,数组就是类似['uses' => 'Controller@action', 'middleware' => '...']这种形式的。如果action是Controller@action类型的路由将被转换为action数组, convertToControllerAction执行完后action的内容为:


 
  1. [
  2. 'uses' => 'App\Http\Controllers\SomeController@someAction',
  3. 'controller' => 'App\Http\Controllers\SomeController@someAction'
  4. ]

可以看到把命名空间补充到了控制器的名称前组成了完整的控制器类名,action数组构建完成接下里就是创建路由了,创建路由即用指定的HTTP请求方法、URI字符串和action数组来创建\Illuminate\Routing\Route类的实例:


 
  1. protected function newRoute($methods, $uri, $action)
  2. {
  3. return (new Route($methods, $uri, $action))
  4. ->setRouter($this)
  5. ->setContainer($this->container);
  6. }

路由创建完成后将Route添加到RouteCollection中去:


 
  1. protected function addRoute($methods, $uri, $action)
  2. {
  3. return $this->routes->add($this->createRoute($methods, $uri, $action));
  4. }

router的$routes属性就是一个RouteCollection对象,添加路由到RouteCollection对象时会更新RouteCollection对象的routes、allRoutes、nameList和actionList属性


 
  1. class RouteCollection implements Countable, IteratorAggregate
  2. {
  3. public function add(Route $route)
  4. {
  5. $this->addToCollections($route);
  6.  
  7. $this->addLookups($route);
  8.  
  9. return $route;
  10. }
  11.  
  12. protected function addToCollections($route)
  13. {
  14. $domainAndUri = $route->getDomain().$route->uri();
  15.  
  16. foreach ($route->methods() as $method) {
  17. $this->routes[$method][$domainAndUri] = $route;
  18. }
  19.  
  20. $this->allRoutes[$method.$domainAndUri] = $route;
  21. }
  22.  
  23. protected function addLookups($route)
  24. {
  25. $action = $route->getAction();
  26.  
  27. if (isset($action['as'])) {
  28. //如果时命名路由,将route对象映射到以路由名为key的数组值中方便查找
  29. $this->nameList[$action['as']] = $route;
  30. }
  31.  
  32. if (isset($action['controller'])) {
  33. $this->addToActionList($action, $route);
  34. }
  35. }
  36.  
  37. }
  38.  

RouteCollection的四个属性

routes中存放了HTTP请求方法与路由对象的映射:


 
  1. [
  2. 'GET' => [
  3. $routeUri1 => $routeObj1
  4. ...
  5. ]
  6. ...
  7. ]

allRoutes属性里存放的内容时将routes属性里的二位数组编程一位数组后的内容:


 
  1. [
  2. 'GET' . $routeUri1 => $routeObj1
  3. 'GET' . $routeUri2 => $routeObj2
  4. ...
  5. ]

nameList是路由名称与路由对象的一个映射表


 
  1. [
  2. $routeName1 => $routeObj1
  3. ...
  4. ]

actionList是路由控制器方法字符串与路由对象的映射表


 
  1. [
  2. 'App\Http\Controllers\ControllerOne@ActionOne' => $routeObj1
  3. ]

这样就算注册好路由了。

路由寻址

中间件的文章里我们说过HTTP请求在经过Pipeline通道上的中间件的前置操作后到达目的地:


 
  1. //Illuminate\Foundation\Http\Kernel
  2. class Kernel implements KernelContract
  3. {
  4. protected function sendRequestThroughRouter($request)
  5. {
  6. $this->app->instance('request', $request);
  7.  
  8. Facade::clearResolvedInstance('request');
  9.  
  10. $this->bootstrap();
  11.  
  12. return (new Pipeline($this->app))
  13. ->send($request)
  14. ->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware)
  15. ->then($this->dispatchToRouter());
  16. }
  17.  
  18. protected function dispatchToRouter()
  19. {
  20. return function ($request) {
  21. $this->app->instance('request', $request);
  22.  
  23. return $this->router->dispatch($request);
  24. };
  25. }
  26.  
  27. }

上面代码可以看到Pipeline的destination就是dispatchToRouter函数返回的闭包:


 
  1. $destination = function ($request) {
  2. $this->app->instance('request', $request);
  3. return $this->router->dispatch($request);
  4. };

在闭包里调用了router的dispatch方法,路由寻址就发生在dispatch的第一个阶段findRoute里:


 
  1. class Router implements RegistrarContract, BindingRegistrar
  2. {
  3. public function dispatch(Request $request)
  4. {
  5. $this->currentRequest = $request;
  6.  
  7. return $this->dispatchToRoute($request);
  8. }
  9.  
  10. public function dispatchToRoute(Request $request)
  11. {
  12. return $this->runRoute($request, $this->findRoute($request));
  13. }
  14.  
  15. protected function findRoute($request)
  16. {
  17. $this->current = $route = $this->routes->match($request);
  18.  
  19. $this->container->instance(Route::class, $route);
  20.  
  21. return $route;
  22. }
  23.  
  24. }

寻找路由的任务由 RouteCollection 负责,这个函数负责匹配路由,并且把 request 的 url 参数绑定到路由中:


 
  1. class RouteCollection implements Countable, IteratorAggregate
  2. {
  3. public function match(Request $request)
  4. {
  5. $routes = $this->get($request->getMethod());
  6.  
  7. $route = $this->matchAgainstRoutes($routes, $request);
  8.  
  9. if (! is_null($route)) {
  10. //找到匹配的路由后,将URI里的路径参数绑定赋值给路由(如果有的话)
  11. return $route->bind($request);
  12. }
  13.  
  14. $others = $this->checkForAlternateVerbs($request);
  15.  
  16. if (count($others) > 0) {
  17. return $this->getRouteForMethods($request, $others);
  18. }
  19.  
  20. throw new NotFoundHttpException;
  21. }
  22.  
  23. protected function matchAgainstRoutes(array $routes, $request, $includingMethod = true)
  24. {
  25. return Arr::first($routes, function ($value) use ($request, $includingMethod) {
  26. return $value->matches($request, $includingMethod);
  27. });
  28. }
  29. }
  30.  
  31. class Route
  32. {
  33. public function matches(Request $request, $includingMethod = true)
  34. {
  35. $this->compileRoute();
  36.  
  37. foreach ($this->getValidators() as $validator) {
  38. if (! $includingMethod && $validator instanceof MethodValidator) {
  39. continue;
  40. }
  41.  
  42. if (! $validator->matches($this, $request)) {
  43. return false;
  44. }
  45. }
  46.  
  47. return true;
  48. }
  49. }

$routes = $this->get($request->getMethod());会先加载注册路由阶段在RouteCollection里生成的routes属性里的值,routes中存放了HTTP请求方法与路由对象的映射。

然后依次调用这堆路由里路由对象的matches方法, matches方法, matches方法里会对HTTP请求对象进行一些验证,验证对应的Validator是:UriValidator、MethodValidator、SchemeValidator、HostValidator。
在验证之前在$this->compileRoute()里会将路由的规则转换成正则表达式。

UriValidator主要是看请求对象的URI是否与路由的正则规则匹配能匹配上:


 
  1. class UriValidator implements ValidatorInterface
  2. {
  3. public function matches(Route $route, Request $request)
  4. {
  5. $path = $request->path() == '/' ? '/' : '/'.$request->path();
  6.  
  7. return preg_match($route->getCompiled()->getRegex(), rawurldecode($path));
  8. }
  9. }

MethodValidator验证请求方法, SchemeValidator验证协议是否正确(http|https), HostValidator验证域名, 如果路由中不设置host属性,那么这个验证不会进行。

一旦某个路由通过了全部的认证就将会被返回,接下来就要将请求对象URI里的路径参数绑定赋值给路由参数:

路由参数绑定


 
  1. class Route
  2. {
  3. public function bind(Request $request)
  4. {
  5. $this->compileRoute();
  6.  
  7. $this->parameters = (new RouteParameterBinder($this))
  8. ->parameters($request);
  9.  
  10. return $this;
  11. }
  12. }
  13.  
  14. class RouteParameterBinder
  15. {
  16. public function parameters($request)
  17. {
  18. $parameters = $this->bindPathParameters($request);
  19.  
  20. if (! is_null($this->route->compiled->getHostRegex())) {
  21. $parameters = $this->bindHostParameters(
  22. $request, $parameters
  23. );
  24. }
  25.  
  26. return $this->replaceDefaults($parameters);
  27. }
  28.  
  29. protected function bindPathParameters($request)
  30. {
  31. preg_match($this->route->compiled->getRegex(), '/'.$request->decodedPath(), $matches);
  32.  
  33. return $this->matchToKeys(array_slice($matches, 1));
  34. }
  35.  
  36. protected function matchToKeys(array $matches)
  37. {
  38. if (empty($parameterNames = $this->route->parameterNames())) {
  39. return [];
  40. }
  41.  
  42. $parameters = array_intersect_key($matches, array_flip($parameterNames));
  43.  
  44. return array_filter($parameters, function ($value) {
  45. return is_string($value) && strlen($value) > 0;
  46. });
  47. }
  48. }

赋值路由参数完成后路由寻址的过程就结束了,结下来就该运行通过匹配路由中对应的控制器方法返回响应对象了。


 
  1. class Router implements RegistrarContract, BindingRegistrar
  2. {
  3. public function dispatch(Request $request)
  4. {
  5. $this->currentRequest = $request;
  6.  
  7. return $this->dispatchToRoute($request);
  8. }
  9.  
  10. public function dispatchToRoute(Request $request)
  11. {
  12. return $this->runRoute($request, $this->findRoute($request));
  13. }
  14.  
  15. protected function runRoute(Request $request, Route $route)
  16. {
  17. $request->setRouteResolver(function () use ($route) {
  18. return $route;
  19. });
  20.  
  21. $this->events->dispatch(new Events\RouteMatched($route, $request));
  22.  
  23. return $this->prepareResponse($request,
  24. $this->runRouteWithinStack($route, $request)
  25. );
  26. }
  27.  
  28. protected function runRouteWithinStack(Route $route, Request $request)
  29. {
  30. $shouldSkipMiddleware = $this->container->bound('middleware.disable') &&
  31. $this->container->make('middleware.disable') === true;
  32. //收集路由和控制器里应用的中间件
  33. $middleware = $shouldSkipMiddleware ? [] : $this->gatherRouteMiddleware($route);
  34.  
  35. return (new Pipeline($this->container))
  36. ->send($request)
  37. ->through($middleware)
  38. ->then(function ($request) use ($route) {
  39. return $this->prepareResponse(
  40. $request, $route->run()
  41. );
  42. });
  43.  
  44. }
  45.  
  46. }
  47.  
  48. namespace Illuminate\Routing;
  49. class Route
  50. {
  51. public function run()
  52. {
  53. $this->container = $this->container ?: new Container;
  54. try {
  55. if ($this->isControllerAction()) {
  56. return $this->runController();
  57. }
  58. return $this->runCallable();
  59. } catch (HttpResponseException $e) {
  60. return $e->getResponse();
  61. }
  62. }
  63.  
  64. }

这里我们主要介绍路由相关的内容,runRoute的过程通过上面的源码可以看到其实也很复杂, 会收集路由和控制器里的中间件,将请求通过中间件过滤才会最终到达目的地路由,执行目的路由地run()方法,里面会判断路由对应的是一个控制器方法还是闭包然后进行相应地调用,最后把执行结果包装成Response对象返回给客户端。这个过程还会涉及到我们以前介绍过的中间件过滤、服务解析、依赖注入方面的信息,如果在看源码时有不懂的地方可以翻看我之前写的文章。

  1. 依赖注入
  2. 服务容器
  3. 中间件

 联系我们

  • 邮箱:admin@admincms.top
  • 官方博客:blog.admincms.top
  • 官方微信公众号:huayuejishu
扫描二维码关注Joker.Liu微信公众号
TOP博客官方微信公众号二维码