Laravel版本:5.3以上
源碼路徑:vendor/laravel/framework/src/Illuminate/Routing
門面(別名):Illuminate\Support\Facades\Route
服務提供者:
map觸發流程
夫類:Illuminate\Foundation\Support\Providers\RouteServiceProvider
? ? 子類向外服務觸發 public function boot()?--->
? ? 內部調用 protected function loadRoutes()--->
? ? ?觸發子類map方法 $this->app->call([$this, 'map'])
向往提供子類:App\Providers\RouteServiceProvider
map加載內容
Api路由:
????$this->mapApiRoutes();?protected權限,不可以隨意調用
? ??加載routes/api.php文件,并默認使用api中間件。可以通過控制api中間件來控制api的所有路由。
? ??Route::prefix('api') ->middleware('api') ->namespace($this->namespace) ->group(base_path('routes/api.php'));
Web路由:
????$this->mapWebRoutes();?protected權限,不可以隨意調用
? ? 加載routes/web.php文件,并默認使用web中間件??梢酝ㄟ^控制web中間件來控制web的所有路由。
????????Route::middleware('web') ->namespace($this->namespace) ->group(base_path('routes/web.php'));
最容易疑惑的地方
?Route::middleware('web') ->namespace($this->namespace) ->group(base_path('routes/web.php'));
這語句中的group,如果看成是
vendor/laravel/framework/src/Illuminate/Routing/Router.php中的group方法,那就會更加迷惑了。
可以嘗試?Route::group(base_path('routes/web.php'));
其實這里的group方法是調vendor/laravel/framework/src/Illuminate/Routing/RouteRegistrar.php 中的group方法。
具體流程如下
實例化Application
vendor/laravel/framework/src/Illuminate/Foundation/Application.php
protected function registerBaseServiceProviders()
{
? ? $this->register(new EventServiceProvider($this));
? ? $this->register(new LogServiceProvider($this));
? ? $this->register(new RoutingServiceProvider($this)); //注冊路由
}
實例化路由
vendor/laravel/framework/src/Illuminate/Routing/RoutingServiceProvider.php
注冊路由:
protected function registerRouter()
{
? ? $this->app->singleton('router', function ($app) {
? ? ? ? return new Router($app['events'], $app);
});
}
注冊門面(別名)
/Volumes/data/source/zhonghui/vendor/laravel/framework/src/Illuminate/Support/Facades/Route.php
protected static function getFacadeAccessor()
{
? ? return 'router';
}
聲明門面(別名)
config/app.php中
'Route' => Illuminate\Support\Facades\Route::class,
調用ResourceRegistrar
vendor/laravel/framework/src/Illuminate/Routing/Router.php
public function __call($method, $parameters)
{
? ? if (static::hasMacro($method)) {
? ? ? ? return $this->macroCall($method, $parameters);
}
? ? return (new RouteRegistrar($this))->attribute($method, $parameters[0]);
}
看這里就能解析為什么Route::group(base_path('routes/web.php'))會報錯。因為這樣寫會調用Router里面的group方法,但是Route先調用'as', 'domain', 'middleware', 'name', 'namespace', 'prefix'這幾個方法,就不會調用Router里面的group。因為會觸發__call方法進入ResourceRegistrar中。
vendor/laravel/framework/src/Illuminate/Routing/ResourceRegistrar.php
public function group($callback)
{
? ? $this->router->group($this->attributes, $callback);
}
以上就是route部分簡要解析,有空會把剩下的解析分享給大家。