[关闭]
@Chiang 2021-04-17T11:46:29.000000Z 字数 6006 阅读 585

Service Providers

LaravelDoc 2021-04


Introduction

Service providers are the central place of all Laravel application bootstrapping. Your own application, as well as all of Laravel's core services, are bootstrapped via service providers.

But, what do we mean by "bootstrapped"? In general, we mean registering things, including registering service container bindings, event listeners, middleware, and even routes. Service providers are the central place to configure your application.

If you open the config/app.php file included with Laravel, you will see a providers array. These are all of the service provider classes that will be loaded for your application. By default, a set of Laravel core service providers are listed in this array. These providers bootstrap the core Laravel components, such as the mailer, queue, cache, and others. Many of these providers are "deferred" providers, meaning they will not be loaded on every request, but only when the services they provide are actually needed.

In this overview, you will learn how to write your own service providers and register them with your Laravel application.

If you would like to learn more about how Laravel handles requests and works internally, check out our documentation on the Laravel request lifecycle.

Writing Service Providers

All service providers extend the Illuminate\Support\ServiceProvider class. Most service providers contain a register and a boot method. Within the register method, you should only bind things into the service container. You should never attempt to register any event listeners, routes, or any other piece of functionality within the register method.

The Artisan CLI can generate a new provider via the make:provider command:

  1. php artisan make:provider RiakServiceProvider

The Register Method

As mentioned previously, within the register method, you should only bind things into the service container. You should never attempt to register any event listeners, routes, or any other piece of functionality within the register method. Otherwise, you may accidentally use a service that is provided by a service provider which has not loaded yet.

Let's take a look at a basic service provider. Within any of your service provider methods, you always have access to the $app property which provides access to the service container:

  1. namespace App\Providers;
  2. use App\Services\Riak\Connection;
  3. use Illuminate\Support\ServiceProvider;
  4. class RiakServiceProvider extends ServiceProvider
  5. {
  6. /**
  7. * Register any application services.
  8. *
  9. * @return void
  10. */
  11. public function register()
  12. {
  13. $this->app->singleton(Connection::class, function ($app) {
  14. return new Connection(config('riak'));
  15. });
  16. }
  17. }

This service provider only defines a register method, and uses that method to define an implemention of App\Services\Riak\Connection in the service container. if you're not yet familiar with Laravel's service container, check out its documenttation.

The bindings And singletons Properties

If your service provider registers many simple bindings, you may wish to use the bindings and singletons properties instead of menually registering each container binding. When the service provider is loaded by the framework, it will automatically check for these properties and register their bindings:

  1. namespace App\Providers;
  2. use Illuminate\Support\ServiceProvider;
  3. ...
  4. class AppserviceProvider extends ServiceProvider
  5. {
  6. /**
  7. * All of the container bindings that should be registered.
  8. *
  9. * @var array
  10. */
  11. public $bindings = [
  12. ServerProvider::class => DigitalOceanServerProvider::class,
  13. ];
  14. /**
  15. * All of the container bindings that should be registered.
  16. *
  17. * @var array
  18. */
  19. public $singletons = [
  20. DowntimeNotifier::class => PingdomDowntimeNotifier::class,
  21. ServerProvider::class => ServerToolsProvider::class,
  22. ];
  23. }

The Boot Method

So, what if we need to register a view composer within our service provider? This should be done within the boot method. This method is called after all other service providers have been registered, meaning you have access to all other services that have been registered by the framework:

  1. namespace App\Providers;
  2. use Illuminate\Support\Facades\View;
  3. use Illuminate\Support\ServiceProvider;
  4. class ComposerServiceProvider extends ServiceProvider
  5. {
  6. /**
  7. * Bootstrap any application services.
  8. *
  9. * @return void
  10. */
  11. public function boot()
  12. {
  13. View::composer('view', function(){
  14. //
  15. });
  16. }
  17. }

Boot Method Dependency Injection

You may type-hint dependencies for your service provider's boot method. The Service container will automatically inject any dependencies you need:

  1. use Illuminate\Contracts\Routing\ResponseFactory;
  2. /**
  3. * Bootstrap any application services.
  4. *
  5. * @param \Illuminate\Contracts\Routing\ResponseFactory $response
  6. * @return void
  7. */
  8. public function boot(ResponseFactory $response)
  9. {
  10. $response->macro('serialized', function ($value){
  11. //
  12. });
  13. }

Registering Providers

All service providers are registered in the config/app.php configuration file. This file contains a providers array where you can list the class names of your service providers. By default, a set of Laravel core service providers are listed in this array. These providers bootstrap the core Laravel componects, such as the mailer, queue, cache, and others.

To register your provider, add it to the array:

  1. 'providers' => [
  2. // Other Service Providers
  3. App\Providers\ComposerServiceProvider::class,
  4. ],

Deferred Providers

If your provider is only registering binding in the service container, you may choose to defer its registration until one of the registered bindings is actually needed. Deferring the loading of such a provider will improve the performance of your application, since it is not loaded from the filesystem on every request.

Laravel compiles and stores a list of all of the services supplied by deferred service providers, along with the name of its service provider class. Then, only when you attempt to resolve one of these services does Laravel load the service provider.

To defer the loading of a provider, implement the \Illuminate\Contracts\SupportDeferrableProvider interface and define a provides method. The provides method should return the service container bindings registered by the provider:

  1. namespace App\Providers;
  2. use App\Services\Riak\Connection;
  3. use Illuminate\Contracts\Support\DeferrableProvider;
  4. use Illuminate\Support\ServiceProvider;
  5. class RiakServiceProvider extends ServiceProvider implements DeferrableProvider
  6. {
  7. /**
  8. * Register any application services.
  9. *
  10. * @return void
  11. */
  12. public function register()
  13. {
  14. $this->app->singleton(Connection::class, function ($app){
  15. return new Connection($app['config']['riak']);
  16. });
  17. }
  18. /**
  19. * Get the services provided by the provider.
  20. *
  21. * @return array
  22. */
  23. public function provides()
  24. {
  25. return [Connection::class];
  26. }
  27. }

Service Providers

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注