1. 程式人生 > >laravel5.5 自定義defer service provider的寫法

laravel5.5 自定義defer service provider的寫法

文章目錄

場景

  • 像文件描述的那樣,defer service provider 不是沒有每個請求都要載入的,所以可以提高應用的響應效率。defer service provider只會在需要的時候才會載入。 那麼應該怎麼操作

參考文件

解決

  • YourServiceProvider需要設定 $defer 屬性 && provides 方法
    • protected $defer = true;
    • The provides method should return the service container bindings registered by the provider
      翻譯一下就是providers 需要返回service container
  /**
     * Get the services provided by the provider.
     *
     * @return array
     */
   public function provides()
    {
        return [Connection::class];
    }

舉例

<?php

namespace App\Providers;

use App\Billing\Stripe;
use Illuminate\Support\ServiceProvider
; class BillServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Bootstrap the application services. * * @return void */ public function boot() { }
/** * Register the application services. * * @return void */ public function register() { $this->app->singleton('billing', function($app){ return new Stripe(); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['billing']; } }