Laravel核心代碼學習 -- 路由

路由

路由是外界訪問Laravel應用程序的通路或者說路由定義了Laravel的應用程序向外界提供服務的具體方式:經過指定的URI、HTTP請求方法以及路由參數(可選)才能正確訪問到路由定義的處理程序。不管URI對應的處理程序是一個簡單的閉包仍是說是控制器方法沒有對應的路由外界都訪問不到他們,今天咱們就來看看Laravel是如何來設計和實現路由的。php

咱們在路由文件裏一般是向下面這樣來定義路由的:laravel

Route::get('/user', 'UsersController@index');
複製代碼

經過上面的路由咱們能夠知道,客戶端經過以HTTP GET方式來請求 URI "/user"時,Laravel會把請求最終派發給UsersController類的index方法來進行處理,而後在index方法中返回響應給客戶端。git

上面註冊路由時用到的Route類在Laravel裏叫門面(Facade),它提供了一種簡單的方式來訪問綁定到服務容器裏的服務router,Facade的設計理念和實現方式我打算之後單開博文來寫,在這裏咱們只要知道調用的Route這個門面的靜態方法都對應服務容器裏router這個服務的方法,因此上面那條路由你也能夠當作是這樣來註冊的:github

app()->make('router')->get('user', 'UsersController@index');
複製代碼

router這個服務是在實例化應用程序Application時在構造方法裏經過註冊RoutingServiceProvider時綁定到服務容器裏的:web

//bootstrap/app.php
$app = new Illuminate\Foundation\Application(
    realpath(__DIR__.'/../')
);

//Application: 構造方法
public function __construct($basePath = null)
{
    if ($basePath) {
        $this->setBasePath($basePath);
    }

    $this->registerBaseBindings();

    $this->registerBaseServiceProviders();

    $this->registerCoreContainerAliases();
}

//Application: 註冊基礎的服務提供器
protected function registerBaseServiceProviders()
{
    $this->register(new EventServiceProvider($this));

    $this->register(new LogServiceProvider($this));

    $this->register(new RoutingServiceProvider($this));
}

//\Illuminate\Routing\RoutingServiceProvider: 綁定router到服務容器
protected function registerRouter()
{
    $this->app->singleton('router', function ($app) {
        return new Router($app['events'], $app);
    });
}
複製代碼

經過上面的代碼咱們知道了Route調用的靜態方法都對應於\Illuminate\Routing\Router類裏的方法,Router這個類裏包含了與路由的註冊、尋址、調度相關的方法。正則表達式

下面咱們從路由的註冊、加載、尋址這幾個階段來看一下laravel裏是如何實現這些的。bootstrap

路由加載

註冊路由前須要先加載路由文件,路由文件的加載是在App\Providers\RouteServiceProvider這個服務器提供者的boot方法里加載的:api

class RouteServiceProvider extends ServiceProvider
{
    public function boot()
    {
        parent::boot();
    }

    public function map()
    {
        $this->mapApiRoutes();

        $this->mapWebRoutes();
    }

    protected function mapWebRoutes()
    {
        Route::middleware('web')
             ->namespace($this->namespace)
             ->group(base_path('routes/web.php'));
    }

    protected function mapApiRoutes()
    {
        Route::prefix('api')
             ->middleware('api')
             ->namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    }
}
複製代碼
namespace Illuminate\Foundation\Support\Providers;

class RouteServiceProvider extends ServiceProvider
{

    public function boot()
    {
        $this->setRootControllerNamespace();

        if ($this->app->routesAreCached()) {
            $this->loadCachedRoutes();
        } else {
            $this->loadRoutes();

            $this->app->booted(function () {
                $this->app['router']->getRoutes()->refreshNameLookups();
                $this->app['router']->getRoutes()->refreshActionLookups();
            });
        }
    }

    protected function loadCachedRoutes()
    {
        $this->app->booted(function () {
            require $this->app->getCachedRoutesPath();
        });
    }

    protected function loadRoutes()
    {
        if (method_exists($this, 'map')) {
            $this->app->call([$this, 'map']);
        }
    }
}

class Application extends Container implements ApplicationContract, HttpKernelInterface
{
    public function routesAreCached()
    {
        return $this['files']->exists($this->getCachedRoutesPath());
    }

    public function getCachedRoutesPath()
    {
        return $this->bootstrapPath().'/cache/routes.php';
    }
}
複製代碼

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類裏的方法:

public function get($uri, $action = null)
{
    return $this->addRoute(['GET', 'HEAD'], $uri, $action);
}

public function post($uri, $action = null)
{
    return $this->addRoute('POST', $uri, $action);
}
....
複製代碼

能夠看到路由的註冊統一都是由router類的addRoute方法來處理的:

//註冊路由到RouteCollection
protected function addRoute($methods, $uri, $action)
{
    return $this->routes->add($this->createRoute($methods, $uri, $action));
}

//建立路由
protected function createRoute($methods, $uri, $action)
{
    if ($this->actionReferencesController($action)) {
    	//controller@action類型的路由在這裏要進行轉換
        $action = $this->convertToControllerAction($action);
    }

    $route = $this->newRoute(
        $methods, $this->prefix($uri), $action
    );

    if ($this->hasGroupStack()) {
        $this->mergeGroupAttributesIntoRoute($route);
    }

    $this->addWhereClausesToRoute($route);

    return $route;
}

protected function convertToControllerAction($action)
{
    if (is_string($action)) {
        $action = ['uses' => $action];
    }

    if (! empty($this->groupStack)) {        
        $action['uses'] = $this->prependGroupNamespace($action['uses']);
    }
    
    $action['controller'] = $action['uses'];

    return $action;
}
複製代碼

註冊路由時傳遞給addRoute的第三個參數action能夠閉包、字符串或者數組,數組就是相似['uses' => 'Controller@action', 'middleware' => '...']這種形式的。若是action是Controller@action類型的路由將被轉換爲action數組, convertToControllerAction執行完後action的內容爲:

[
	'uses' => 'App\Http\Controllers\SomeController@someAction',
	'controller' => 'App\Http\Controllers\SomeController@someAction'
]
複製代碼

能夠看到把命名空間補充到了控制器的名稱前組成了完整的控制器類名,action數組構建完成接下里就是建立路由了,建立路由即用指定的HTTP請求方法、URI字符串和action數組來建立\Illuminate\Routing\Route類的實例:

protected function newRoute($methods, $uri, $action)
{
    return (new Route($methods, $uri, $action))
                ->setRouter($this)
                ->setContainer($this->container);
}
複製代碼

路由建立完成後將Route添加到RouteCollection中去:

protected function addRoute($methods, $uri, $action)
{
    return $this->routes->add($this->createRoute($methods, $uri, $action));
}
複製代碼

router的$routes屬性就是一個RouteCollection對象,添加路由到RouteCollection對象時會更新RouteCollection對象的routes、allRoutes、nameList和actionList屬性

class RouteCollection implements Countable, IteratorAggregate
{
    public function add(Route $route)
    {
        $this->addToCollections($route);

        $this->addLookups($route);

        return $route;
    }
    
    protected function addToCollections($route)
    {
        $domainAndUri = $route->getDomain().$route->uri();

        foreach ($route->methods() as $method) {
            $this->routes[$method][$domainAndUri] = $route;
        }

        $this->allRoutes[$method.$domainAndUri] = $route;
	}
	
    protected function addLookups($route)
    {
        $action = $route->getAction();

        if (isset($action['as'])) {
        	//若是時命名路由,將route對象映射到以路由名爲key的數組值中方便查找
            $this->nameList[$action['as']] = $route;
        }

        if (isset($action['controller'])) {
            $this->addToActionList($action, $route);
        }
    }

}
複製代碼

RouteCollection的四個屬性

routes中存放了HTTP請求方法與路由對象的映射:

[
	'GET' => [
		$routeUri1 => $routeObj1
		...
	]
	...
]
複製代碼

allRoutes屬性裏存放的內容時將routes屬性裏的二維數組變成一維數組後的內容:

[
	'GET' . $routeUri1 => $routeObj1
	'GET' . $routeUri2 => $routeObj2
	...
]
複製代碼

nameList是路由名稱與路由對象的一個映射表

[
	$routeName1 => $routeObj1
	...
]
複製代碼

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

[
	'App\Http\Controllers\ControllerOne@ActionOne' => $routeObj1
]
複製代碼

這樣就算註冊好路由了。

路由尋址

在後面中間件的文章裏咱們看到HTTP請求是在通過Pipeline通道上的中間件的前置操做後到達目的地:

//Illuminate\Foundation\Http\Kernel
class Kernel implements KernelContract
{
    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);
        };
    }
    
}
複製代碼

上面代碼能夠看到Pipeline的destination就是dispatchToRouter函數返回的閉包:

$destination = function ($request) {
    $this->app->instance('request', $request);
    return $this->router->dispatch($request);
};
複製代碼

在閉包裏調用了router的dispatch方法,路由尋址就發生在dispatch的第一個階段findRoute裏:

class Router implements RegistrarContract, BindingRegistrar
{	
    public function dispatch(Request $request)
    {
        $this->currentRequest = $request;

        return $this->dispatchToRoute($request);
    }
    
    public function dispatchToRoute(Request $request)
    {
        return $this->runRoute($request, $this->findRoute($request));
    }
    
    protected function findRoute($request)
    {
        $this->current = $route = $this->routes->match($request);

        $this->container->instance(Route::class, $route);

        return $route;
    }
    
}
複製代碼

尋找路由的任務由 RouteCollection 負責,這個函數負責匹配路由,而且把 request 的 url 參數綁定到路由中:

class RouteCollection implements Countable, IteratorAggregate
{
    public function match(Request $request)
    {
        $routes = $this->get($request->getMethod());

        $route = $this->matchAgainstRoutes($routes, $request);

        if (! is_null($route)) {
            //找到匹配的路由後,將URI裏的路徑參數綁定賦值給路由(若是有的話)
            return $route->bind($request);
        }

        $others = $this->checkForAlternateVerbs($request);

        if (count($others) > 0) {
            return $this->getRouteForMethods($request, $others);
        }

        throw new NotFoundHttpException;
    }

    protected function matchAgainstRoutes(array $routes, $request, $includingMethod = true)
    {
        return Arr::first($routes, function ($value) use ($request, $includingMethod) {
            return $value->matches($request, $includingMethod);
        });
    }
}

class Route
{
    public function matches(Request $request, $includingMethod = true)
    {
        $this->compileRoute();

        foreach ($this->getValidators() as $validator) {
            if (! $includingMethod && $validator instanceof MethodValidator) {
                continue;
            }

            if (! $validator->matches($this, $request)) {
                return false;
            }
        }

        return true;
    }
}
複製代碼

$routes = $this->get($request->getMethod());會先加載註冊路由階段在RouteCollection裏生成的routes屬性裏的值,routes中存放了HTTP請求方法與路由對象的映射。

而後依次調用這堆路由里路由對象的matches方法, matches方法, matches方法裏會對HTTP請求對象進行一些驗證,驗證對應的Validator是:UriValidator、MethodValidator、SchemeValidator、HostValidator。 在驗證以前在$this->compileRoute()裏會將路由的規則轉換成正則表達式。

UriValidator主要是看請求對象的URI是否與路由的正則規則匹配能匹配上:

class UriValidator implements ValidatorInterface
{
    public function matches(Route $route, Request $request)
    {
        $path = $request->path() == '/' ? '/' : '/'.$request->path();

        return preg_match($route->getCompiled()->getRegex(), rawurldecode($path));
    }
}
複製代碼

MethodValidator驗證請求方法, SchemeValidator驗證協議是否正確(http|https), HostValidator驗證域名, 若是路由中不設置host屬性,那麼這個驗證不會進行。

一旦某個路由經過了所有的認證就將會被返回,接下來就要將請求對象URI裏的路徑參數綁定複製給路由參數:

路由參數綁定

class Route
{
    public function bind(Request $request)
    {
        $this->compileRoute();

        $this->parameters = (new RouteParameterBinder($this))
                        ->parameters($request);

        return $this;
    }
}

class RouteParameterBinder
{
    public function parameters($request)
    {
        $parameters = $this->bindPathParameters($request);

        if (! is_null($this->route->compiled->getHostRegex())) {
            $parameters = $this->bindHostParameters(
                $request, $parameters
            );
        }

        return $this->replaceDefaults($parameters);
    }
    
    protected function bindPathParameters($request)
    {
            preg_match($this->route->compiled->getRegex(), '/'.$request->decodedPath(), $matches);

            return $this->matchToKeys(array_slice($matches, 1));
    }
    
    protected function matchToKeys(array $matches)
    {
        if (empty($parameterNames = $this->route->parameterNames())) {
            return [];
        }

        $parameters = array_intersect_key($matches, array_flip($parameterNames));

        return array_filter($parameters, function ($value) {
            return is_string($value) && strlen($value) > 0;
        });
    }
}

複製代碼

賦值路由參數完成後路由尋址的過程就結束了,結下來就該運行經過匹配路由中對應的控制器方法返回響應對象了。

namespace Illuminate\Routing;
class Router implements RegistrarContract, BindingRegistrar
{	
    public function dispatch(Request $request)
    {
        $this->currentRequest = $request;

        return $this->dispatchToRoute($request);
    }
    
    public function dispatchToRoute(Request $request)
    {
        return $this->runRoute($request, $this->findRoute($request));
    }
    
    protected function runRoute(Request $request, Route $route)
    {
        $request->setRouteResolver(function () use ($route) {
            return $route;
        });

        $this->events->dispatch(new Events\RouteMatched($route, $request));

        return $this->prepareResponse($request,
            $this->runRouteWithinStack($route, $request)
        );
    }
    
    protected function runRouteWithinStack(Route $route, Request $request)
    {
        $shouldSkipMiddleware = $this->container->bound('middleware.disable') &&
                            $this->container->make('middleware.disable') === true;
	//收集路由和控制器裏應用的中間件
        $middleware = $shouldSkipMiddleware ? [] : $this->gatherRouteMiddleware($route);

        return (new Pipeline($this->container))
                    ->send($request)
                    ->through($middleware)
                    ->then(function ($request) use ($route) {
                        return $this->prepareResponse(
                            $request, $route->run()
                        );
                    });
    
    }
}

namespace Illuminate\Routing;
class Route
{
    public function run()
    {
        $this->container = $this->container ?: new Container;
        try {
            if ($this->isControllerAction()) {
                return $this->runController();
            }
            return $this->runCallable();
        } catch (HttpResponseException $e) {
            return $e->getResponse();
        }
    }

}
複製代碼

這裏咱們主要介紹路由相關的內容,runRoute的過程經過上面的源碼能夠看到其實也很複雜, 會收集路由和控制器裏的中間件,將請求經過中間件過濾纔會最終到達目的地路由,執行目的路由地run()方法,裏面會判斷路由對應的是一個控制器方法仍是閉包而後進行相應地調用,最後把執行結果包裝成Response對象返回給客戶端。 下一節咱們就來學習一下這裏提到的中間件。

本文已經收錄在系列文章Laravel源碼學習裏,歡迎訪問閱讀。

相關文章
相關標籤/搜索