今天這篇博文來探索一下laravel的路由。在第一篇講laravel入口文件的博文里,我們就提到過laravel的路由是在application對象的初始化階段,通過provider來加載的。這個路由服務提供者注冊於vendor\laravel\framework\src\Illuminate\Foundation\Application.php的registerBaseServiceProviders方法
protected function registerBaseServiceProviders() { $this->register(new EventServiceProvider($this)); $this->register(new LogServiceProvider($this)); $this->register(new RoutingServiceProvider($this)); }
可以看到這個方法對路由provider進行了注冊,我們最開始的博文也提到過,這個register方法實際上是運行了provider內部的register方法,現在來看一下這個provider都提供了些什么vendor\laravel\framework\src\Illuminate\Routing\RoutingServiceProvider.php
public function register() { $this->registerRouter(); $this->registerUrlGenerator(); $this->registerRedirector(); $this->registerPsrRequest(); $this->registerPsrResponse(); $this->registerResponseFactory(); $this->registerControllerDispatcher(); }
這個服務提供者類中將許多對象都添加到了laravel的容器中,其中最重要的就是第一個注冊的Router類了。Router中包含了我們寫在路由文件中的get、post等各種方法,我們在路由文件中所使用的Route::any()方法也是一個門面類,它所代理的對象便是Router。
看過了路由的初始化,再來看一下我們在路由文件中所書寫的路由是在什么時候加載到系統中的。在config/app.php文件中的privders數組中有一個名為RouteServiceProvider的服務提供者會跟隨laravel系統在加載配置的時候一起加載。這個文件位於\app\Providers\RouteServiceProvider.php剛剛的Routing對路由服務進行了注冊,這里的RouteServiceProvider就要通過剛剛加載的系統類來加載我們寫在routes路由文件夾中的路由了。
至於這個provider是何時開始啟動的,還記得我們第一篇博客中介紹的Illuminate\Foundation\Bootstrap\BootProviders這個provider嗎?這個provider在注冊時便會將已經注冊過的provider,通過application中的boot方法,轉發到它們自身的boot方法來啟動了。
而RouteServiceProvider這個類的boot方法通過它父類boot方法繞了一圈后又運行了自己的mapWebRoutes方法。
//Illuminate\Foundation\Support\Providers\RouteServiceProvider.php public function boot() { //設置路由中控制器的命名空間 $this->setRootControllerNamespace(); //若路由已有緩存則加載緩存 if ($this->app->routesAreCached()) { $this->loadCachedRoutes(); } else { //這個方法啟動了子類中的map方法來加載路由 $this->loadRoutes(); $this->app->booted(function () { $this->app['router']->getRoutes()->refreshNameLookups(); $this->app['router']->getRoutes()->refreshActionLookups(); }); } } protected function loadRoutes() { if (method_exists($this, 'map')) { //這里又把視線拉回了子類,執行了子類中的map方法 $this->app->call([$this, 'map']); } }
這里這個mapWebRoutes方法有點繞,它先是通過門面類將Route變成了Router對象,接着又調用了Router中不存在的方法middleware,通過php的魔術方法__call將執行對象變成了RouteRegistrar對象(\Illuminate\Routing\RouteRegistrar.php)在第三句調用group方法時,又將路由文件的地址傳入了Router方法的group方法中。
protected function mapWebRoutes() { //這里的route門面指向依舊是router,middleware方法通過__call重載將對象指向了RouteRegistrar對象 Route::middleware('web') //RouteRegistrar對象也加載了命名空間 ->namespace($this->namespace) //這里RouteRegistrar對象中的group方法又將對象方法指向了Router中的group方法 ->group(base_path('routes/web.php')); }
//Router類 public function __call($method, $parameters) { if (static::hasMacro($method)) { return $this->macroCall($method, $parameters); } //在這里通過重載實例化對象 if ($method == 'middleware') { return (new RouteRegistrar($this))->attribute($method, is_array($parameters[0]) ? $parameters[0] : $parameters); } return (new RouteRegistrar($this))->attribute($method, $parameters[0]); }
//\Illuminate\Routing\RouteRegistrar.php public function group($callback) { $this->router->group($this->attributes, $callback); }
//Router類 public function group(array $attributes, $routes) { //更新路由棧這個數組 $this->updateGroupStack($attributes); // Once we have updated the group stack, we'll load the provided routes and // merge in the group's attributes when the routes are created. After we // have created the routes, we will pop the attributes off the stack. $this->loadRoutes($routes); //出棧 array_pop($this->groupStack); } protected function loadRoutes($routes) { //這里判斷閉包是因為laravel的路由文件中也允許我們使用group對路由進行分組 if ($routes instanceof Closure) { $routes($this); } else { $router = $this; //傳入的$routes是一個文件路徑,在這里將其引入執行,在這里就開始一條一條的導入路由了 require $routes; } }
繞了這么一大圈終於把寫在routes文件夾中的路由文件加載進laravel系統了。接下來的操作就比較簡單了。
先來看一下我的路由文件中寫了些什么。
路由文件中只寫了兩個路由,在Route加載后通過dd(app()->router);打印出來看一下吧。
剛剛我們看見了路由中的get、post、put等數組,那么現在來看一下它們是怎么被添加到路由數組中的
1 public static $verbs = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']; 2 3 public function any($uri, $action = null) 4 { 5 return $this->addRoute(self::$verbs, $uri, $action); 6 } 7 8 public function get($uri, $action = null) 9 { 10 return $this->addRoute(['GET', 'HEAD'], $uri, $action); 11 } 12 13 public function post($uri, $action = null) 14 { 15 return $this->addRoute('POST', $uri, $action); 16 } 17 18 public function put($uri, $action = null) 19 { 20 return $this->addRoute('PUT', $uri, $action); 21 } 22 23 public function patch($uri, $action = null) 24 { 25 return $this->addRoute('PATCH', $uri, $action); 26 } 27 28 public function delete($uri, $action = null) 29 { 30 return $this->addRoute('DELETE', $uri, $action); 31 } 32 33 public function options($uri, $action = null) 34 { 35 return $this->addRoute('OPTIONS', $uri, $action); 36 } 37 38 public function any($uri, $action = null) 39 { 40 return $this->addRoute(self::$verbs, $uri, $action); 41 }
通過上面的代碼,我們可以發現,包括any在內的各種方式添加的路由都是通過addroute這個方法來添加的,將寫在路由文件中的uri和控制器或閉包傳入其中。
這里的路由添加過程中對路由進行了多次包裝,這么多次調用所做的事情簡單來說就兩點。
1、將路由添加至route對象。
2、在路由集合中建立路由字典數組,用於后續步驟快速查找路由
這里詳細分解一下路由創建的過程
一、這里我們先把流程從addRoute走到createRoute這個方法中來,首先判斷了路由是否為控制器,方法很簡單就不貼出來了。在15行更新控制器命名空間時,跳到下面的代碼塊。
1 protected function addRoute($methods, $uri, $action) 2 { 3 //這里的routes是在構造方法中添加的對象RouteCollection,methods是剛剛傳入的get等傳輸方式 4 return $this->routes->add($this->createRoute($methods, $uri, $action)); 5 } 6 7 protected function createRoute($methods, $uri, $action) 8 { 9 // If the route is routing to a controller we will parse the route action into 10 // an acceptable array format before registering it and creating this route 11 // instance itself. We need to build the Closure that will call this out. 12 //判斷傳入的action是否為控制器而不是閉包函數 13 if ($this->actionReferencesController($action)) { 14 //更新控制器命名空間 15 $action = $this->convertToControllerAction($action); 16 } 17 //這里的prefix方法用於獲取在group處定義的路由前綴,newRoute方法再次將路由包裝 18 $route = $this->newRoute( 19 $methods, $this->prefix($uri), $action 20 ); 21 22 // If we have groups that need to be merged, we will merge them now after this 23 // route has already been created and is ready to go. After we're done with 24 // the merge we will be ready to return the route back out to the caller. 25 if ($this->hasGroupStack()) { 26 //將本次加載的路由組合並至對象屬性 27 $this->mergeGroupAttributesIntoRoute($route); 28 } 29 30 //為路由參數添加where限制 31 $this->addWhereClausesToRoute($route); 32 33 return $route; 34 }
二、這里是更新控制器命名空間的部分,這里跑完后再次回到上面那個代碼塊的19行,這里獲取了路由前綴,方法很簡單就不貼出來了。然后將get等方法數組,路由前綴與action操作作為參數生成一個路由對象,再跳到下一個代碼塊。
1 protected function convertToControllerAction($action) 2 { 3 if (is_string($action)) { 4 $action = ['uses' => $action]; 5 } 6 7 // Here we'll merge any group "uses" statement if necessary so that the action 8 // has the proper clause for this property. Then we can simply set the name 9 // of the controller on the action and return the action array for usage. 10 //路由組棧不為空的話,還記得之前路由服務boot的時候調用的group方法嗎? 11 if (! empty($this->groupStack)) { 12 //更新傳入控制器的命名空間 13 $action['uses'] = $this->prependGroupNamespace($action['uses']); 14 } 15 16 // Here we will set this controller name on the action array just so we always 17 // have a copy of it for reference if we need it. This can be used while we 18 // search for a controller name or do some other type of fetch operation. 19 $action['controller'] = $action['uses']; 20 21 return $action; 22 } 23 24 protected function prependGroupNamespace($class) 25 { 26 $group = end($this->groupStack); 27 //返回帶有命名空間的控制器全稱 28 return isset($group['namespace']) && strpos($class, '\\') !== 0 29 ? $group['namespace'].'\\'.$class : $class; 30 }
三、這個代碼塊new出了route,后續的setrouter與setContainer分別為該對象傳入了router與容器對象。route對象在構造方法中進行簡單賦值后,通過routerAction對象的parse方法將路由再次進行包裝,並設置了路由的前綴,這個方法比較簡單就不貼代碼了。這個時候再次調回步驟一的第25行,判斷路由分組的棧是否為空,將剛剛添加的路由與原路由組合並(路由組將web.php文件看做一個路由分組,我們自己寫在路由文件中的group被看做是這個分組中的子分組)。這里合並分組的代碼也比較簡單,記住各個屬性的作用很容易看懂,就不貼出來了。包括再后面的添加where部分也是,值得一提的是route對象中有一個getAction方法,其中調用到了Arr底層對象。這個對象目前對我們來說過於底層了,追蹤到這里就好,不需要再往下追溯下去了。這個時候,返回的route變量就作為步驟一第4行的add方法的參數了。見下方代碼塊。
1 protected function newRoute($methods, $uri, $action) 2 { 3 return (new Route($methods, $uri, $action)) 4 ->setRouter($this) 5 ->setContainer($this->container); 6 } 7 8 9 //laravel\framework\src\Illuminate\Routing\Route.php 10 public function __construct($methods, $uri, $action) 11 { 12 $this->uri = $uri; 13 $this->methods = (array) $methods; 14 //將路由操作解析成數組 15 $this->action = $this->parseAction($action); 16 17 if (in_array('GET', $this->methods) && ! in_array('HEAD', $this->methods)) { 18 $this->methods[] = 'HEAD'; 19 } 20 21 if (isset($this->action['prefix'])) { 22 $this->prefix($this->action['prefix']); 23 } 24 } 25 26 protected function parseAction($action) 27 { 28 return RouteAction::parse($this->uri, $action); 29 } 30 31 //\vendor\laravel\framework\src\Illuminate\Routing\RouteAction.php 32 public static function parse($uri, $action) 33 { 34 // If no action is passed in right away, we assume the user will make use of 35 // fluent routing. In that case, we set a default closure, to be executed 36 // if the user never explicitly sets an action to handle the given uri. 37 //如果為空操作將會返回一個報錯信息的閉包 38 if (is_null($action)) { 39 return static::missingAction($uri); 40 } 41 42 // If the action is already a Closure instance, we will just set that instance 43 // as the "uses" property, because there is nothing else we need to do when 44 // it is available. Otherwise we will need to find it in the action list. 45 //在這里已經成為閉包的action 會直接返回數組 46 47 if (is_callable($action)) { 48 return ['uses' => $action]; 49 } 50 51 // If no "uses" property has been set, we will dig through the array to find a 52 // Closure instance within this list. We will set the first Closure we come 53 // across into the "uses" property that will get fired off by this route. 54 elseif (! isset($action['uses'])) { 55 $action['uses'] = static::findCallable($action); 56 } 57 58 if (is_string($action['uses']) && ! Str::contains($action['uses'], '@')) { 59 $action['uses'] = static::makeInvokable($action['uses']); 60 } 61 62 return $action; 63 }
四、這一部分就是之前說的創建路由查找字典的部分了。代碼比較簡單。
1 //\laravel\framework\src\Illuminate\Routing\RouteCollection.php 2 public function add(Route $route) 3 { 4 //將路由添加到集合 5 $this->addToCollections($route); 6 //將路由添加到一個多維數組中方便作為字典來查找 7 $this->addLookups($route); 8 9 return $route; 10 } 11 12 protected function addToCollections($route) 13 { 14 //獲取為路由定義的域,若有domain屬性則返回http或https中的一個?這里沒看懂,不過最終還是返回了uri 15 $domainAndUri = $route->getDomain().$route->uri(); 16 //獲取到了路由內的get等方法,遍歷添加到routes中 17 foreach ($route->methods() as $method) { 18 $this->routes[$method][$domainAndUri] = $route; 19 } 20 21 $this->allRoutes[$method.$domainAndUri] = $route; 22 } 23 24 protected function addLookups($route) 25 { 26 // If the route has a name, we will add it to the name look-up table so that we 27 // will quickly be able to find any route associate with a name and not have 28 // to iterate through every route every time we need to perform a look-up. 29 //獲取action 30 $action = $route->getAction(); 31 32 //若有as關鍵字則添加相應的數組屬性方便作為字典來查詢 33 if (isset($action['as'])) { 34 $this->nameList[$action['as']] = $route; 35 } 36 37 // When the route is routing to a controller we will also store the action that 38 // is used by the route. This will let us reverse route to controllers while 39 // processing a request and easily generate URLs to the given controllers. 40 if (isset($action['controller'])) { 41 $this->addToActionList($action, $route); 42 } 43 } 44 45 protected function addToActionList($action, $route) 46 { 47 //再次通過controller作為標示存儲route路由 48 $this->actionList[trim($action['controller'], '\\')] = $route; 49 }
走完這個留流程,路由就被加載完成了。程序的流程就回到了boot部分的group方法了。