diff --git a/container.md b/container.md index fb9291f707e..b0c14c0148c 100644 --- a/container.md +++ b/container.md @@ -9,6 +9,7 @@ - [Binding Typed Variadics](#binding-typed-variadics) - [Tagging](#tagging) - [Extending Bindings](#extending-bindings) + - [Binding Tags](#binding-tags) - [Resolving](#resolving) - [The Make Method](#the-make-method) - [Automatic Injection](#automatic-injection) @@ -221,6 +222,46 @@ Once the services have been tagged, you may easily resolve them all via the `tag return new ReportAggregator($app->tagged('reports')); }); + + +### Binding Tags + +If a class needs an array of instances or a variadic constructor argument, you can instruct the container to resolve that dependency with tagged services. + +To bind services tagged as "reports" to a primitive (`array`) constructor argument named `$reports`: + + class ReportAggregator + { + /** @var Report[] */ + public $reports; + + public function __construct(array $reports) + { + $this->reports = $reports; + } + } + + $this->app->when(ReportAggregator::class) + ->needs('$reports') + ->giveTagged('reports'); + +To bind services tagged as "reports" to a variadic constructor argument typed `Report`: + + class ReportAggregator + { + /** @var Report[] */ + public $reports; + + public function __construct(Report ...$reports) + { + $this->reports = $reports; + } + } + + $this->app->when(ReportAggregator::class) + ->needs(Report::class) + ->giveTagged('reports'); + ### Extending Bindings