这篇文章来自一个 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