這篇文章來自一個 sf 社區問題的思考php
1 . 首先, 你注意一下 /config/app.php
裏面web
/* |-------------------------------------------------------------------------- | Class Aliases |-------------------------------------------------------------------------- | | This array of class aliases will be registered when this application | is started. However, feel free to register as many as you wish as | the aliases are "lazy" loaded so they don't hinder performance. | */ 'aliases' => [ 'Route' => Illuminate\Support\Facades\Route::class, ];
2 . 由於有 Facades
, 因此咱們直接去看 Illuminate\Support\Facades\Route::class
這個類返回的內容app
* @method static \Illuminate\Routing\Route get(string $uri, \Closure|array|string $action) /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return 'router'; }
3 . 那就簡單了, 直接去找註冊爲 router
的組件ide
發現是在 Illuminate/Routing/RoutingServiceProvider.php
this
/** * Register the router instance. * * @return void */ protected function registerRouter() { $this->app->singleton('router', function ($app) { return new Router($app['events'], $app); }); }
4 . new Router()
看到了沒, 很顯然就會返回 Illuminate/Routing/Router.php
實例; 是否是發現了spa
/** * Register a new GET route with the router. * * @param string $uri * @param \Closure|array|string|null $action * @return \Illuminate\Routing\Route */ public function get($uri, $action = null) { return $this->addRoute(['GET', 'HEAD'], $uri, $action); }
1) . 我確認了 'router' 是在Illuminate/Routing/RoutingServiceProvider.php
裏面的 ,code
可是爲何沒有配置在 /config/app.php
的 providers
裏面呢component
Illuminate/Foundation/Application.php
orm
注意 base service providers
和 configured providers
/** * Register all of the base service providers. * * @return void */ protected function registerBaseServiceProviders() { $this->register(new EventServiceProvider($this)); $this->register(new LogServiceProvider($this)); $this->register(new RoutingServiceProvider($this)); } /** * Register all of the configured providers. * * @return void */ public function registerConfiguredProviders() { (new ProviderRepository($this, new Filesystem, $this->getCachedServicesPath())) ->load($this->config['app.providers']); }
2) . 那我看到在 /config/app.php
註冊了一個看起來像路由相關的 App\Providers\RouteServiceProvider::class,
它是幹嗎用的呢?
首先 App\Providers\RouteServiceProvider
繼承自 Illuminate\Foundation\Support\Providers\RouteServiceProvider
; (而且調用了咱們上面的 Illuminate\Support\Facades\Route
, 能夠使用 Route::*
)
直接看看 Illuminate\Foundation\Support\Providers\RouteServiceProvider
你就會明白
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(); }); } } public function register() { // 沒有在這裏註冊 }
boot 方法是在全部服務提供者都註冊完成後調用的方法, 因此說 這是啓動後 註冊路由的 provider