laravel的服务提供者是什么

2020-08-13 19:31:37

如果你使用过 Laravel 框架的话,那么,你不可能没听说过服务容器服务提供者。事实上,它们是 Lavavel 框架核心,它们完成 Larvel 应用中服务启动的艰巨任务。

在这篇文章中,我们将给大家介绍laravel的服务提供者是什么?

在学习服务提供者之前,先简单介绍一下服务容器,服务容器会在服务提供者中被经常使用。

简而言之,Laravel 服务容器 是一个用于存储绑定组件的盒子,它还会为应用提供所需的服务。

Laravel 文档中描述如下:

Laravel 服务容器是用于管理类的依赖和执行依赖注入的工具 - Laravel 文档

这样,当我们需要注入一个内置的组件或服务时,可以在构造函数或方法中使用类型提示功能注入,然后在使用时从服务容器中自动解析出所需实例及其依赖!是不是很酷?这个功能可以让我们从手动管理组件中解脱出来,从而降低系统耦合度。

让我们看一个简单实例来加深理解。

<?phpClass SomeClass{    public function __construct(FooBar $foobarObject)    {        // use $foobarObject object    }}

如你所见,SomeClass 需要使用 FooBar 实例。换句话说它需要依赖其它组件。Laravel 实现自动注入需要从服务容器中查找并执行注入适当的依赖。

如果你希望了解 Laravel 是如何知道需要将哪个组件或服务绑定到服务容器中的,答案是通过服务提供者实现的。服务提供者完成将组件绑定到服务容器的工作。在服务提供者内部,这个工作被称之为服务容器绑定,绑定处理由服务提供者完成。

服务提供者实现了服务绑定,绑定处理则由 register 方法完成。

同时,这又会引入一个新的问题:Laravel 是如何知道有哪些服务提供者的呢?这个我们貌似还没有讨论到吧?我到时看到,之前有说 Laravel 会自动的去查找到服务!朋友,你的问题太多了:Laravel 只是一个框架,它不是一个超级英雄,不是么?我们当然需要去明确的告知 Laravel 框架我们有哪些服务提供者。

让我们来瞧瞧 config/app.php 配置文件。你会找到一个用于 Laravel 应用启动过程中被载入的服务提供者配置列表。

'providers' => [        /*         * Laravel Framework Service Providers...         */        IlluminateAuthAuthServiceProvider::class,        IlluminateBroadcastingBroadcastServiceProvider::class,        IlluminateBusBusServiceProvider::class,        IlluminateCacheCacheServiceProvider::class,        IlluminateFoundationProvidersConsoleSupportServiceProvider::class,        IlluminateCookieCookieServiceProvider::class,        IlluminateDatabaseDatabaseServiceProvider::class,        IlluminateEncryptionEncryptionServiceProvider::class,        IlluminateFilesystemFilesystemServiceProvider::class,        IlluminateFoundationProvidersFoundationServiceProvider::class,        IlluminateHashingHashServiceProvider::class,        IlluminateMailMailServiceProvider::class,        IlluminateNotificationsNotificationServiceProvider::class,        IlluminatePaginationPaginationServiceProvider::class,        IlluminatePipelinePipelineServiceProvider::class,        IlluminateQueueQueueServiceProvider::class,        IlluminateRedisRedisServiceProvider::class,        IlluminateAuthPasswordsPasswordResetServiceProvider::class,        IlluminateSessionSessionServiceProvider::class,        IlluminateTranslationTranslationServiceProvider::class,        IlluminateValidationValidationServiceProvider::class,        IlluminateViewViewServiceProvider::class,        /*         * Package Service Providers...         */        LaravelTinkerTinkerServiceProvider::class,        /*         * Application Service Providers...         */        AppProvidersAppServiceProvider::class,        AppProvidersAuthServiceProvider::class,        // AppProvidersBroadcastServiceProvider::class,        AppProvidersEventServiceProvider::class,        AppProvidersRouteServiceProvider::class,],