服务提供器(Service Providers)

Laravel 的核心服务都是通过服务提供器启动。启动即注册服务的意思,包括注册服务容器绑定、事件监听器、中间件甚至路由。

注册服务提供器

应用要加载的所有服务提供者信息保存于 config/app.php 配置文件

  • 很多服务提供者都是延迟加载的, 即只有使用到它们时才会进行加载
  • 需要注册自己的服务提供者, 追加到 provides 数组即可

示例代码

  1. 'providers' => [
  2. /*
  3. * Laravel Framework Service Providers...
  4. */
  5. Illuminate\Auth\AuthServiceProvider::class,
  6. Illuminate\Broadcasting\BroadcastServiceProvider::class,
  7. Illuminate\Bus\BusServiceProvider::class,
  8. Illuminate\Cache\CacheServiceProvider::class,
  9. Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
  10. Illuminate\Cookie\CookieServiceProvider::class,
  11. Illuminate\Database\DatabaseServiceProvider::class,
  12. Illuminate\Encryption\EncryptionServiceProvider::class,
  13. Illuminate\Filesystem\FilesystemServiceProvider::class,
  14. Illuminate\Foundation\Providers\FoundationServiceProvider::class,
  15. Illuminate\Hashing\HashServiceProvider::class,
  16. Illuminate\Mail\MailServiceProvider::class,
  17. Illuminate\Notifications\NotificationServiceProvider::class,
  18. Illuminate\Pagination\PaginationServiceProvider::class,
  19. Illuminate\Pipeline\PipelineServiceProvider::class,
  20. Illuminate\Queue\QueueServiceProvider::class,
  21. Illuminate\Redis\RedisServiceProvider::class,
  22. Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
  23. Illuminate\Session\SessionServiceProvider::class,
  24. Illuminate\Translation\TranslationServiceProvider::class,
  25. Illuminate\Validation\ValidationServiceProvider::class,
  26. Illuminate\View\ViewServiceProvider::class,
  27. /*
  28. * Package Service Providers...
  29. */
  30. Mews\Captcha\CaptchaServiceProvider::class,
  31. /*
  32. * Application Service Providers...
  33. */
  34. App\Providers\AppServiceProvider::class,
  35. App\Providers\AuthServiceProvider::class,
  36. // App\Providers\BroadcastServiceProvider::class,
  37. App\Providers\EventServiceProvider::class,
  38. App\Providers\RouteServiceProvider::class,
  39. ],

自定义服务提供器

所有的服务提供器都继承自 Illuminate\Support\ServiceProvider

创建服务提供器

使用 artisan 命令生成服务提供器,服务提供器的命名通常为 XXXX + ServiceProvider

php artisan make:provider MoeServiceProvider

主要实现的方法

大部分服务提供者都包含两个方法:registerboot

register 方法

注册服务提供者, 只负责绑定服务到服务容器, 不要在该方法中注册事件监听器, 路由或任何其它功能

示例代码

public function register() {
    $this->app->singleton(Connection::class, function ($app) {
        return new Connection(config('moe'));
    });
}

boot 方法

待补充