Laravel 8 綁定變長參數(shù)類型

2021-07-02 20:50 更新

有時(shí),您可能有一個(gè)使用可變參數(shù)構(gòu)造函數(shù)參數(shù)接收類型化對(duì)象數(shù)組的類:

class Firewall
{
    protected $logger;
    protected $filters;

    public function __construct(Logger $logger, Filter ...$filters)
    {
        $this->logger = $logger;
        $this->filters = $filters;
    }
} 

使用上下文綁定,您可以通過給 give 方法提供一個(gè) Closure 來解決此依賴關(guān)系,該 Closure 返回已解析的 Filter 實(shí)例的數(shù)組:

$this->app->when(Firewall::class)
          ->needs(Filter::class)
          ->give(function ($app) {
                return [
                    $app->make(NullFilter::class),
                    $app->make(ProfanityFilter::class),
                    $app->make(TooLongFilter::class),
                ];
          });

為了方便起見,您還可以只提供一個(gè)類名稱數(shù)組,以便在 Firewall 需要 Filter 實(shí)例時(shí)由容器解析:

$this->app->when(Firewall::class)
          ->needs(Filter::class)
          ->give([
              NullFilter::class,
              ProfanityFilter::class,
              TooLongFilter::class,
          ]);
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)