资讯专栏INFORMATION COLUMN

深入剖析 Laravel 服务提供者实现原理

yeooo / 537人阅读

摘要:服务提供者启动原理之前我们有学习深度挖掘生命周期和深入剖析服务容器,今天我们将学习服务提供者。的所有核心服务都是通过服务提供者进行引导启动的,所以想深入了解那么研究服务提供者的原理是个绕不开的话题。

</>复制代码

  1. 本文首发于 深入剖析 Laravel 服务提供者实现原理,转载请注明出处。

今天我们将学习 Laravel 框架另外一个核心内容「服务提供者(Service Provider)」。服务提供者的功能是完成 Laravel 应用的引导启动,或者说是将 Laravel 中的各种服务「注册」到「Laravel 服务容器」,这样才能在后续处理 HTTP 请求时使用这些服务。

服务提供者基本概念

我们知道 「服务提供者」是配置应用的中心,它的主要工作是使用「服务容器」实现服务容器绑定、事件监听器、中间件,甚至是路由的注册。

除核心服务外,几乎所有的服务提供者都定义在配置文件 config/app.php 文件中的 providers 节点中。

服务提供者的典型处理流程是,当接 Laravel 应用接收到 HTTP 请求时会去执行「服务提供者的 register(注册)」方法,将各个服务「绑定」到容器内;之后,到了实际处理请求阶段,依据使用情况按需加载所需服务。这样的优势很明显能够提升应用的性能。

细心的朋友可能发现这里用了一个词「几乎」,没错还有一些属于核心服务提供者,这些并没有定义在 providers 配置节点中而是直接由 IlluminateFoundationApplication 服务容器直接在实例化阶段就完成了注册服务。

</>复制代码

  1. registerBaseServiceProviders();
  2. ...
  3. }
  4. /**
  5. * Register all of the base service providers. 注册应用基础服务提供者
  6. *
  7. * @return void
  8. */
  9. protected function registerBaseServiceProviders()
  10. {
  11. $this->register(new EventServiceProvider($this));
  12. $this->register(new LogServiceProvider($this));
  13. $this->register(new RoutingServiceProvider($this));
  14. }

对服务容器不是很熟悉的老铁可以阅读 深入剖析 Laravel 服务容器,并且在文中「注册基础服务提供者」一节也有详细分析服务容器是如何注册服务提供者的。

另外一个,我们还需要了解的是所有的服务提供者都继承自 IlluminateSupportServiceProvider 类。不过对于我们来说目前还无需研究基类,所以我们将焦点放到如何实现一个自定义的服务提供者,然后还有两个需要掌握方法。

服务提供者入门 创建自定义服务提供者

要创建自定义的「服务提供者」,可以直接使用 Laravel 内置的 artisan 命令完成。

</>复制代码

  1. php artisan make:provider RiskServiceProvider

这个命令会在 app/Providers 目录下创建 RiskServiceProvider.php 文件,打开文件内容如下:

</>复制代码

  1. register 方法
  2. register 方法中,我们无需处理业务逻辑,在这个方法中你只需去处理「绑定」服务到服务容器中即可。

  3. 从文档中我们知道:

  4. </>复制代码

    1. register 方法中,你只需要将类绑定到 服务容器 中。而不需要尝试在 register 方法中注册任何事件监听器、路由或者任何其他功能。否则,你可能会意外使用到尚未加载的服务提供器提供的服务。
  5. 如何理解这句话的含义呢?

  6. 如果你有了解过服务容器运行原理,就会知道在「绑定」操作仅仅是建立起接口和实现的对应关系,此时并不会创建具体的实例,即不会存在真实的依赖关系。直到某个服务真的被用到时才会从「服务容器」中解析出来,而解析的过程发生在所有服务「注册」完成之后。

  7. 一旦我们尝试在 register 注册阶段使用某些未被加载的服务依赖,即这个服务目前还没有被注册所以不可用。

  8. 这样就需要在「注册」绑定时,同时需要关注服务的注册顺序,但这一点 Laravel 并不作出任何保证。

  9. 理解了这个道理,我们就可以随便进入一个「服务提供者」来看看其中的 register 方法的逻辑,现在我们挑选的是 IlluminateCacheCacheServiceProvider 服务作为讲解:

  10. </>复制代码

    1. app->singleton("cache", function ($app) {
    2. return new CacheManager($app);
    3. });
    4. $this->app->singleton("cache.store", function ($app) {
    5. return $app["cache"]->driver();
    6. });
    7. $this->app->singleton("memcached.connector", function () {
    8. return new MemcachedConnector;
    9. });
    10. }
    11. /**
    12. * Get the services provided by the provider.
    13. *
    14. * @return array
    15. */
    16. public function provides()
    17. {
    18. return [
    19. "cache", "cache.store", "memcached.connector",
    20. ];
    21. }
    22. }
  11. 没错,如你所预料的一样,它的 register 方法执行了三个单例绑定操作,仅此而已。

  12. 简单注册服务
  13. 对于处理复杂绑定逻辑,可以自定义「服务提供者」。但是如果是比较简单的注册服务,有没有比较方便的绑定方法呢?毕竟,并不是每个服务都会有复杂的依赖处理。

  14. 我们可以从 文档 中得到解答:

  15. </>复制代码

    1. 如果你的服务提供商注册许多简单的绑定,你可能想使用 bindingssingletons 属性而不是手动注册每个容器绑定。
  16. </>复制代码

    1. DigitalOceanServerProvider::class,
    2. ];
    3. /**
    4. * 设定单例模式的容器绑定对应关系
    5. *
    6. * @var array
    7. */
    8. public $singletons = [
    9. DowntimeNotifier::class => PingdomDowntimeNotifier::class,
    10. ];
    11. }
  17. 此时,通过 bingdingssingletons 成员变量来设置简单的绑定,就可以避免大量的「服务提供者」类的生成了。

  18. boot 方法
  19. 聊完了 register 方法,接下来进入另一个主题,来研究一下服务提供者的 boot 方法。

  20. 通过前面的学习,我们知道在 register 方法中 Laravel 并不能保证所有其他服务已被加载。所以当需要处理具有依赖关系的业务逻辑时,应该将这些逻辑处理放置到 boot 方法内。在 boot 方法中我们可以去完成:注册事件监听器、引入路由文件、注册过滤器等任何你可以想象得到的业务处理。

  21. config/app.php 配置中我们可以看到如下几个服务提供者:

  22. </>复制代码

    1. /*
    2. * Application Service Providers...
    3. */
    4. AppProvidersAppServiceProvider::class,
    5. AppProvidersAuthServiceProvider::class,
    6. // AppProvidersBroadcastServiceProvider::class,
    7. AppProvidersEventServiceProvider::class,
    8. AppProvidersRouteServiceProvider::class,
  23. 选择其中的 AppProvidersRouteServiceProvider::class 服务提供者它继承自 IlluminateFoundationSupportProvidersRouteServiceProvider 基类来看下:

  24. </>复制代码

    1. // 实现类
    2. class RouteServiceProvider extends ServiceProvider
    3. {
    4. /**
    5. * This namespace is applied to your controller routes. In addition, it is set as the URL generator"s root namespace.
    6. */
    7. protected $namespace = "AppHttpControllers";
    8. /**
    9. * Define your route model bindings, pattern filters, etc.
    10. */
    11. public function boot()
    12. {
    13. parent::boot();
    14. }
    15. /**
    16. * Define the routes for the application. 定义应用路由
    17. */
    18. public function map()
    19. {
    20. $this->mapApiRoutes();
    21. $this->mapWebRoutes();
    22. }
    23. /**
    24. * Define the "web" routes for the application. These routes all receive session state, CSRF protection, etc.
    25. * 定义 web 路由。web 路由支持会话状态和 CSRF 防御中间件等。
    26. */
    27. protected function mapWebRoutes()
    28. {
    29. Route::middleware("web")
    30. ->namespace($this->namespace)
    31. ->group(base_path("routes/web.php"));
    32. }
    33. /**
    34. * Define the "api" routes for the application. These routes are typically stateless.
    35. * 定义 api 路由。api 接口路由支持典型的 HTTP 无状态协议。
    36. */
    37. protected function mapApiRoutes()
    38. {
    39. Route::prefix("api")
    40. ->middleware("api")
    41. ->namespace($this->namespace)
    42. ->group(base_path("routes/api.php"));
    43. }
    44. }
  25. 基类 IlluminateFoundationSupportProvidersRouteServiceProvider:

  26. </>复制代码

    1. // 基类
    2. namespace IlluminateFoundationSupportProviders;
    3. /**
    4. * @mixin IlluminateRoutingRouter
    5. */
    6. class RouteServiceProvider extends ServiceProvider
    7. {
    8. /**
    9. * The controller namespace for the application.
    10. */
    11. protected $namespace;
    12. /**
    13. * Bootstrap any application services. 引导启动服务
    14. */
    15. public function boot()
    16. {
    17. $this->setRootControllerNamespace();
    18. // 如果已缓存路由,从缓存文件中载入路由
    19. if ($this->app->routesAreCached()) {
    20. $this->loadCachedRoutes();
    21. } else {
    22. //还没有路由缓存,加载路由
    23. $this->loadRoutes();
    24. $this->app->booted(function () {
    25. $this->app["router"]->getRoutes()->refreshNameLookups();
    26. $this->app["router"]->getRoutes()->refreshActionLookups();
    27. });
    28. }
    29. }
    30. /**
    31. * Load the application routes. 加载应用路由,调用实例的 map 方法,该方法定义在 AppProvidersRouteServiceProvider::class 中。
    32. */
    33. protected function loadRoutes()
    34. {
    35. if (method_exists($this, "map")) {
    36. $this->app->call([$this, "map"]);
    37. }
    38. }
    39. }
  27. 对于 RouteServiceProvider 来讲,它的 boot 方法在处理一个路由载入的问题:

  28. 判断是否已有路由缓存;

  29. 有路由缓存,则直接载入路由缓存;

  30. 无路由缓存,执行 map 方法载入路由。

  31. 感兴趣的朋友可以自行了解下 Application Service Providers 配置节点的相关服务提供者,这边不再赘述。

  32. 配置服务提供者
  33. 了解完「服务提供者」两个重要方法后,我们还需要知道 Laravel 是如何查找到所有的服务提供者的。这个超找的过程就是去读取 config/app.php 文件中的 providers 节点内所有的「服务提供器」。

  34. 具体的读取过程我们也会在「服务提供者启动原理」一节中讲解。

  35. 延迟绑定服务提供者
  36. 对于一个项目来说,除了要让它跑起来,往往我们还需要关注它的性能问题。

  37. 当我们打开 config/app.php 配置文件时,你会发现有配置很多服务提供者,难道所有的都需要去执行它的 registerboot 方法么?

  38. 对于不会每次使用的服务提供者很明显,无需每次注册和启动,直到需要用到它的时候。

  39. 为了解决这个问题 Laravel 内置支持 延迟服务提供者 功能,启用时延迟功能后,当它真正需要注册绑定时才会执行 register 方法,这样就可以提升我们服务的性能了。

  40. 启用「延迟服务提供者」功能,需要完成两个操作配置:

  41. 在对应服务提供者中将 defer 属性设置为 true

  42. 并定义 provides 方法,方法返回在提供者 register 方法内需要注册的服务接口名称。

  43. 我们拿 config/app.php 配置中的 BroadcastServiceProvider 作为演示说明:

  44. </>复制代码

    1. app->singleton(BroadcastManager::class, function ($app) {
    2. return new BroadcastManager($app);
    3. });
    4. $this->app->singleton(BroadcasterContract::class, function ($app) {
    5. return $app->make(BroadcastManager::class)->connection();
    6. });
    7. $this->app->alias(
    8. BroadcastManager::class, BroadcastingFactory::class
    9. );
    10. }
    11. /**
    12. * Get the services provided by the provider. 获取提供者所提供的服务接口名称。
    13. */
    14. public function provides()
    15. {
    16. return [
    17. BroadcastManager::class,
    18. BroadcastingFactory::class,
    19. BroadcasterContract::class,
    20. ];
    21. }
    22. }
  45. 小结
  46. 在「服务提供者入门」这个小节我们学习了服务提供者的基本使用和性能优化相关知识,包括:

  47. 如何创建自定义的服务提供者;

  48. 创建 register 方法注册服务到 Laravel 服务容器;

  49. 创建 boot 方法启动服务提供者的引导程序;

  50. 配置我们的服务提供者到 config/app.php 文件,这样才能在容器中加载相应服务;

  51. 通过延迟绑定技术,提升 Laravel 服务性能。

  52. 下一小节,我们将焦点转移到「服务提供者」的实现原理中,深入到 Laravel 内核中去探索「服务提供者」如何被注册和启动,又是如何能够通过延迟技术提升 Laravel 应用的性能的。

  53. 服务提供者启动原理
  54. 之前我们有学习 深度挖掘 Laravel 生命周期 和 深入剖析 Laravel 服务容器,今天我们将学习「服务提供者」。

  55. Laravel 的所有核心服务都是通过服务提供者进行引导启动的,所以想深入了解 Laravel 那么研究「服务提供者」的原理是个绕不开的话题。

  56. 引导程序的启动流程
  57. 服务提供者 注册引导启动 直到处理 HTTP 请求阶段才开始。所以我们直接进入到 AppConsoleKernel::class 类,同时这个类继承于 IlluminateFoundationHttpKernel 类。

  58. IlluminateFoundationHttpKernel 类中我们可以看到如下内容:

  59. </>复制代码

    1. class Kernel implements KernelContract
    2. {
    3. ...
    4. /**
    5. * The bootstrap classes for the application. 应用引导类
    6. */
    7. protected $bootstrappers = [
    8. ...
    9. IlluminateFoundationBootstrapRegisterProviders::class, // 用于注册(register)「服务提供者」的引导类
    10. IlluminateFoundationBootstrapBootProviders::class, // 用于启动(boot)「服务提供者」的引导类
    11. ];
    12. /**
    13. * Handle an incoming HTTP request. 处理 HTTP 请求
    14. */
    15. public function handle($request)
    16. {
    17. try {
    18. $request->enableHttpMethodParameterOverride();
    19. $response = $this->sendRequestThroughRouter($request);
    20. } catch (Exception $e) {
    21. ...
    22. } catch (Throwable $e) {
    23. ...
    24. }
    25. ...
    26. }
    27. /**
    28. * Send the given request through the middleware / router. 对 HTTP 请求执行中间件处理后再发送到指定路由。
    29. */
    30. protected function sendRequestThroughRouter($request)
    31. {
    32. ...
    33. // 1. 引导类引导启动。
    34. $this->bootstrap();
    35. // 2. 中间件及请求处理,生成响应并返回响应。
    36. return (new Pipeline($this->app))
    37. ->send($request)
    38. ->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware)
    39. ->then($this->dispatchToRouter());
    40. }
    41. /**
    42. * Bootstrap the application for HTTP requests. 接收 HTTP 请求时启动应用引导程序。
    43. */
    44. public function bootstrap()
    45. {
    46. // 引导类启动由 Application 容器引导启动。
    47. if (! $this->app->hasBeenBootstrapped()) {
    48. $this->app->bootstrapWith($this->bootstrappers());
    49. }
    50. }
    51. }
  60. IlluminateFoundationHttpKernel 我们的内核处理 HTTP 请求时会经过一下两个主要步骤:

  61. 启动引导程序通过 $this->bootstrap() 方法完成,其中包括所有服务提供者的注册和引导处理;

  62. 处理 HTTP 请求(这个问题涉及到中间件、路由及相应处理,本文将不做深入探讨)。

  63. 进入 IlluminateFoundationApplication 容器中的 bootstrapWith() 方法,来看看容器是如何将引导类引导启动的:

  64. </>复制代码

    1. /**
    2. * Run the given array of bootstrap classes. 执行给定引导程序
    3. */
    4. public function bootstrapWith(array $bootstrappers)
    5. {
    6. $this->hasBeenBootstrapped = true;
    7. foreach ($bootstrappers as $bootstrapper) {
    8. $this["events"]->fire("bootstrapping: ".$bootstrapper, [$this]);
    9. // 从容器中解析出实例,然后调用实例的 bootstrap() 方法引导启动。
    10. $this->make($bootstrapper)->bootstrap($this);
    11. $this["events"]->fire("bootstrapped: ".$bootstrapper, [$this]);
    12. }
    13. }
  65. 通过服务容器的 bootstrap() 方法引导启动时,将定义的在 IlluminateFoundationHttpKerne 类中的应用引导类($bootstrappers)交由 Application 服务容器引导启动。其中与「服务提供者」有关的引导类为:

  66. IlluminateFoundationHttpKerne HTTP 内核通过 bootstrap() 方法引导启动时,实际由服务容器(Application)去完成引导启动的工作,并依据定义在 HTTP 内核中的引导类属性配置顺序依次引导启动,最终「服务提供者」的启动顺序是:

  67. 执行「服务提供者」register 方法的引导类:IlluminateFoundationBootstrapRegisterProviders::class,将完成所有定义在 config/app.php 配置中的服务提供者的注册(register)处理;

  68. 执行「服务提供者」boot 方法的引导类:IlluminateFoundationBootstrapBootProviders::class,将完成所有定义在 config/app.php 配置中的服务提供者的启动(boot)处理。

  69. Laravel 执行服务提供者注册(register)处理
  70. 前面说过「服务提供者」的注册由 IlluminateFoundationBootstrapRegisterProviders::class 引导类启动方法(botstrap())完成。

  71. 1. RegisterProviders 引导注册
  72. </>复制代码

    1. registerConfiguredProviders();
    2. }
    3. }
  73. 在其通过调用服务容器的 registerConfiguredProviders() 方法完成引导启动,所以我们需要到容器中一探究竟。

  74. 2. 由服务容器执行配置文件中的所有服务提供者服务完成注册。
  75. </>复制代码

    1. /**
    2. * Register all of the configured providers. 执行所有配置服务提供者完成注册处理。
    3. *
    4. * @see https://github.com/laravel/framework/blob/5.6/src/Illuminate/Foundation/Application.php
    5. */
    6. public function registerConfiguredProviders()
    7. {
    8. $providers = Collection::make($this->config["app.providers"])
    9. ->partition(function ($provider) {
    10. return Str::startsWith($provider, "Illuminate");
    11. });
    12. $providers->splice(1, 0, [$this->make(PackageManifest::class)->providers()]);
    13. // 通过服务提供者仓库(ProviderRepository)加载所有的提供者。
    14. (new ProviderRepository($this, new Filesystem, $this->getCachedServicesPath()))
    15. ->load($providers->collapse()->toArray());
    16. }
  76. 3. 最后由服务提供者仓库(ProviderRepository)执行服务提供者的注册处理。
  77. </>复制代码

    1. loadManifest();
    2. // 首先从服务提供者的缓存清单文件中载入服务提供者集合。其中包含「延迟加载」的服务提供者。
    3. if ($this->shouldRecompile($manifest, $providers)) {
    4. $manifest = $this->compileManifest($providers);
    5. }
    6. // Next, we will register events to load the providers for each of the events
    7. // that it has requested. This allows the service provider to defer itself
    8. // while still getting automatically loaded when a certain event occurs.
    9. foreach ($manifest["when"] as $provider => $events) {
    10. $this->registerLoadEvents($provider, $events);
    11. }
    12. // 到这里,先执行应用必要(贪婪)的服务提供者完成服务注册。
    13. foreach ($manifest["eager"] as $provider) {
    14. $this->app->register($provider);
    15. }
    16. // 最后将所有「延迟加载服务提供者」加入到容器中。
    17. $this->app->addDeferredServices($manifest["deferred"]);
    18. }
    19. /**
    20. * Compile the application service manifest file. 将服务提供者编译到清单文件中缓存起来。
    21. */
    22. protected function compileManifest($providers)
    23. {
    24. // The service manifest should contain a list of all of the providers for
    25. // the application so we can compare it on each request to the service
    26. // and determine if the manifest should be recompiled or is current.
    27. $manifest = $this->freshManifest($providers);
    28. foreach ($providers as $provider) {
    29. // 解析出 $provider 对应的实例
    30. $instance = $this->createProvider($provider);
    31. // 判断当前服务提供者是否为「延迟加载」类行的,是则将其加入到缓存文件的「延迟加载(deferred)」集合中。
    32. if ($instance->isDeferred()) {
    33. foreach ($instance->provides() as $service) {
    34. $manifest["deferred"][$service] = $provider;
    35. }
    36. $manifest["when"][$provider] = $instance->when();
    37. }
    38. // 如果不是「延迟加载」类型的服务提供者,则为贪婪加载必须立即去执行注册方法。
    39. else {
    40. $manifest["eager"][] = $provider;
    41. }
    42. }
    43. // 将归类后的服务提供者写入清单文件。
    44. return $this->writeManifest($manifest);
    45. }
  78. 服务提供者仓库(ProviderRepository) 处理程序中依次执行如下处理:

  79. 如果存在服务提供者缓存清单,则直接读取「服务提供者」集合;

  80. 否则,将从 config/app.php 配置中的服务提供者编译到缓存清单中;编译由 compileManifest() 方法完成; 编译缓存清单时将处理贪婪加载(eager)和延迟加载(deferred)的服务提供者;

  81. 对于贪婪加载的提供者直接执行服务容器的 register 方法完成服务注册;

  82. 将延迟加载提供者加入到服务容器中,按需注册和引导启动。

  83. 最后通过 IlluminateFoundationApplication 容器完成注册处理:

  84. </>复制代码

    1. /**
    2. * Register a service provider with the application. 在应用服务容器中注册一个服务提供者。
    3. */
    4. public function register($provider, $options = [], $force = false)
    5. {
    6. if (($registered = $this->getProvider($provider)) && ! $force) {
    7. return $registered;
    8. }
    9. // 如果给定的服务提供者是接口名称,解析出它的实例。
    10. if (is_string($provider)) {
    11. $provider = $this->resolveProvider($provider);
    12. }
    13. // 服务提供者提供注册方法时,执行注册服务处理
    14. if (method_exists($provider, "register")) {
    15. $provider->register();
    16. }
    17. $this->markAsRegistered($provider);
    18. // 判断 Laravel 应用是否已启动。已启动的话需要去执行启动处理。
    19. if ($this->booted) {
    20. $this->bootProvider($provider);
    21. }
    22. return $provider;
    23. }
  85. 为什么需要判断是否已经启动过呢?

  86. 因为对于延迟加载的服务提供者只有在使用时才会被调用,所以这里需要这样判断,然后再去启动它。

  87. 以上,便是

  88. Laravel 执行服务提供者启动(boot)处理
  89. 「服务提供者」的启动流程和注册流程大致相同,有兴趣的朋友可以深入源码了解一下。

  90. 1. BootProviders 引导启动
  91. </>复制代码

    1. boot();
    2. }
    3. }
  92. 2. 由服务容器执行配置文件中的所有服务提供者服务完成启动。
  93. </>复制代码

    1. /**
    2. * Boot the application"s service providers. 引导启动应用所有服务提供者
    3. *
    4. * @see https://github.com/laravel/framework/blob/5.6/src/Illuminate/Foundation/Application.php
    5. */
    6. public function boot()
    7. {
    8. if ($this->booted) {
    9. return;
    10. }
    11. // Once the application has booted we will also fire some "booted" callbacks
    12. // for any listeners that need to do work after this initial booting gets
    13. // finished. This is useful when ordering the boot-up processes we run.
    14. $this->fireAppCallbacks($this->bootingCallbacks);
    15. // 遍历并执行服务提供者的 boot 方法。
    16. array_walk($this->serviceProviders, function ($p) {
    17. $this->bootProvider($p);
    18. });
    19. $this->booted = true;
    20. $this->fireAppCallbacks($this->bootedCallbacks);
    21. }
    22. /**
    23. * Boot the given service provider. 启动给定服务提供者
    24. */
    25. protected function bootProvider(ServiceProvider $provider)
    26. {
    27. if (method_exists($provider, "boot")) {
    28. return $this->call([$provider, "boot"]);
    29. }
    30. }
  94. 以上便是服务提供者执行 注册绑定服务引导启动 的相关实现。

  95. 但是稍等一下,我们是不是忘记了还有「延迟加载」类型的服务提供者,它们还没有被注册和引导启动呢!

  96. Laravel 如何完成延迟加载类型的服务提供者
  97. 对于延迟加载类型的服务提供者,我们要到使用时才会去执行它们内部的 registerboot 方法。这里我们所说的使用即使需要 解析 它,我们知道解析处理由服务容器完成。

  98. 所以我们需要进入到 IlluminateFoundationApplication 容器中探索 make 解析的一些细节。

  99. </>复制代码

    1. /**
    2. * Resolve the given type from the container. 从容器中解析出给定服务
    3. *
    4. * @see https://github.com/laravel/framework/blob/5.6/src/Illuminate/Foundation/Application.php
    5. */
    6. public function make($abstract, array $parameters = [])
    7. {
    8. $abstract = $this->getAlias($abstract);
    9. // 判断这个接口是否为延迟类型的并且没有被解析过,是则去将它加载到容器中。
    10. if (isset($this->deferredServices[$abstract]) && ! isset($this->instances[$abstract])) {
    11. $this->loadDeferredProvider($abstract);
    12. }
    13. return parent::make($abstract, $parameters);
    14. }
    15. /**
    16. * Load the provider for a deferred service. 加载给定延迟加载服务提供者
    17. */
    18. public function loadDeferredProvider($service)
    19. {
    20. if (! isset($this->deferredServices[$service])) {
    21. return;
    22. }
    23. $provider = $this->deferredServices[$service];
    24. // 如果服务为注册则去注册并从延迟服务提供者集合中删除它。
    25. if (! isset($this->loadedProviders[$provider])) {
    26. $this->registerDeferredProvider($provider, $service);
    27. }
    28. }
    29. /**
    30. * Register a deferred provider and service. 去执行服务提供者的注册方法。
    31. */
    32. public function registerDeferredProvider($provider, $service = null)
    33. {
    34. // Once the provider that provides the deferred service has been registered we
    35. // will remove it from our local list of the deferred services with related
    36. // providers so that this container does not try to resolve it out again.
    37. if ($service) {
    38. unset($this->deferredServices[$service]);
    39. }
    40. // 执行服务提供者注册服务。
    41. $this->register($instance = new $provider($this));
    42. // 执行服务提供者启动服务。
    43. if (! $this->booted) {
    44. $this->booting(function () use ($instance) {
    45. $this->bootProvider($instance);
    46. });
    47. }
    48. }
  100. 总结
  101. 今天我们深入研究了 Laravel 服务提供者的注册和启动的实现原理,希望对大家有所帮助。

  102. 如果对如何自定义服务提供者不甚了解的朋友可以去阅读 Laravel 服务提供者指南 这篇文章。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/28788.html

相关文章

  • 深入剖析 Laravel 服务容器

    摘要:划下重点,服务容器是用于管理类的依赖和执行依赖注入的工具。类的实例化及其依赖的注入,完全由服务容器自动的去完成。 本文首发于 深入剖析 Laravel 服务容器,转载请注明出处。喜欢的朋友不要吝啬你们的赞同,谢谢。 之前在 深度挖掘 Laravel 生命周期 一文中,我们有去探究 Laravel 究竟是如何接收 HTTP 请求,又是如何生成响应并最终呈现给用户的工作原理。 本章将带领大...

    abson 评论0 收藏0
  • 深入浅出 Laravel 的 Facade 外观系统

    摘要:外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。将使用者与子系统从直接耦合,转变成由外观类提供统一的接口给使用者使用,以降低客户端与子系统之间的耦合度。接下来将深入分析外观服务的加载过程。引导程序将在处理请求是完成引导启动。 本文首发于 深入浅出 Laravel 的 Facade 外观系统,转载请注明出处。 今天我们将学习 Laravel 核心架构中的另一个主题「Fac...

    KavenFan 评论0 收藏0
  • Swoft 源码剖析 - 目录

    摘要:作者链接來源简书著作权归作者所有,本文已获得作者授权转载,并对原文进行了重新的排版。同时顺手整理个人对源码的相关理解,希望能够稍微填补学习领域的空白。系列文章只会节选关键代码辅以思路讲解,请自行配合源码阅读。 作者:bromine链接:https://www.jianshu.com/p/2f6...來源:简书著作权归作者所有,本文已获得作者授权转载,并对原文进行了重新的排版。Swoft...

    qpwoeiru96 评论0 收藏0
  • 后端知识拓展 - 收藏集 - 掘金

    摘要:阻塞,非阻塞首先,阻塞这个词来自操作系统的线程进程的状态模型网络爬虫基本原理一后端掘金网络爬虫是捜索引擎抓取系统的重要组成部分。每门主要编程语言现未来已到后端掘金使用和在相同环境各加载多张小图片,性能相差一倍。 2016 年度小结(服务器端方向)| 掘金技术征文 - 后端 - 掘金今年年初我花了三个月的业余时间用 Laravel 开发了一个项目,在此之前,除了去年换工作准备面试时,我并...

    CoderBear 评论0 收藏0
  • 后端知识拓展 - 收藏集 - 掘金

    摘要:阻塞,非阻塞首先,阻塞这个词来自操作系统的线程进程的状态模型网络爬虫基本原理一后端掘金网络爬虫是捜索引擎抓取系统的重要组成部分。每门主要编程语言现未来已到后端掘金使用和在相同环境各加载多张小图片,性能相差一倍。 2016 年度小结(服务器端方向)| 掘金技术征文 - 后端 - 掘金今年年初我花了三个月的业余时间用 Laravel 开发了一个项目,在此之前,除了去年换工作准备面试时,我并...

    Carl 评论0 收藏0

发表评论

0条评论

yeooo

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<