阅读(1570) (9)

Laravel 8 绑定变长参数类型

2021-06-23 10:30:40 更新

有时,您可能有一个使用可变参数构造函数参数接收类型化对象数组的类:

class Firewall
{
    protected $logger;
    protected $filters;

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

使用上下文绑定,您可以通过给 give 方法提供一个 Closure 来解决此依赖关系,该 Closure 返回已解析的 Filter 实例的数组:

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

为了方便起见,您还可以只提供一个类名称数组,以便在 Firewall 需要 Filter 实例时由容器解析:

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