laravel5.5源碼筆記(4、路由)

今天這篇博文來探索一下laravel的路由。在第一篇講laravel入口文件的博文裏,咱們就提到過laravel的路由是在application對象的初始化階段,經過provider來加載的。這個路由服務提供者註冊於vendor\laravel\framework\src\Illuminate\Foundation\Application.php的registerBaseServiceProviders方法php

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.phplaravel

    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。web

看過了路由的初始化,再來看一下咱們在路由文件中所書寫的路由是在何時加載到系統中的。在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方法中。app

    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系統了。接下來的操做就比較簡單了。dom

先來看一下個人路由文件中寫了些什麼。ide

路由文件中只寫了兩個路由,在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和控制器或閉包傳入其中。

這裏的路由添加過程當中對路由進行了屢次包裝,這麼屢次調用所作的事情簡單來講就兩點。

一、將路由添加至route對象。

二、在路由集合中創建路由字典數組,用於後續步驟快速查找路由

 

這裏詳細分解一下路由建立的過程

1、這裏咱們先把流程從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     }

 

2、這裏是更新控制器命名空間的部分,這裏跑完後再次回到上面那個代碼塊的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     }

 

3、這個代碼塊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     }

 

4、這一部分就是以前說的建立路由查找字典的部分了。代碼比較簡單。

 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方法了。

相關文章
相關標籤/搜索