Laravel框架-服务提供者
它是什么:
- 它是一个继承抽象类
Illuminate\Support\ServiceProvider的一个类
主要作用:
- 以优雅的方式将服务绑定到服务容器上。所谓的优雅,说白了就是将绑定代码写到服务提供者的
register()方法中
创建示例:
- 首先是创建服务提供者,可以使用命令
php artisan make:provider xxServiceProvider 来实现。如,我想创建一个Cache 服务提供者,那就执行命令php artisan make:provider CacheServiceProvider来创建 - 其次在服务提供者中添加
boot()与 register()方法,并且在 register()方法里面书写绑定代码。假设需要绑定的服务是实现了CacheServiceInterface 接口的RedisCacheService 服务,代码如下:
public function boot(){}
public function register()
{
$this->app->bind(CacheServiceInterface::class, RedisCacheService::class);
$this->app->bind(RedisCacheService::class, RedisCacheService::class);
$this->app->instance('redisCacheService', new RedisCacheService());
}
- 最后去
config\app.php文件的providers数组中添加服务提供者
'providers' => [
App\Providers\CacheServiceProvider::class,
],
使用示例:
- 查看‘Laravel框架-服务容器’文章的服务解析
- 以依赖注入的形式到类,或者方法中