@@ -511,11 +511,37 @@ Symfony provides a shortcut to inject all services tagged with a specific tag,
511
511
which is a common need in some applications, so you don't have to write a
512
512
compiler pass just for that.
513
513
514
- In the following example, all services tagged with ``app.handler `` are passed as
515
- first constructor argument to the ``App\HandlerCollection `` service:
514
+ Consider the following ``HandlerCollection `` class where you want to inject
515
+ all services tagged with ``app.handler `` into its constructor argument::
516
+
517
+ // src/HandlerCollection.php
518
+ namespace App;
519
+
520
+ class HandlerCollection
521
+ {
522
+ public function __construct(iterable $handlers)
523
+ {
524
+ }
525
+ }
516
526
517
527
.. configuration-block ::
518
528
529
+ .. code-block :: php-attributes
530
+
531
+ // src/HandlerCollection.php
532
+ namespace App;
533
+
534
+ use Symfony\Component\DependencyInjection\Attribute\TaggedIterator;
535
+
536
+ class HandlerCollection
537
+ {
538
+ public function __construct(
539
+ // the attribute must be applied directly to the argument to autowire
540
+ #[TaggedIterator('app.handler')] iterable $handlers
541
+ ) {
542
+ }
543
+ }
544
+
519
545
.. code-block :: yaml
520
546
521
547
# config/services.yaml
@@ -578,35 +604,6 @@ first constructor argument to the ``App\HandlerCollection`` service:
578
604
;
579
605
};
580
606
581
- After compilation the ``HandlerCollection `` service is able to iterate over your
582
- application handlers::
583
-
584
- // src/HandlerCollection.php
585
- namespace App;
586
-
587
- class HandlerCollection
588
- {
589
- public function __construct(iterable $handlers)
590
- {
591
- }
592
- }
593
-
594
- Injecting tagged services can be also be done through autowiring thanks to the
595
- ``#[TaggedIterator] `` attribute. This attribute must be directly used on the
596
- argument to autowire::
597
-
598
- // src/HandlerCollection.php
599
- namespace App;
600
-
601
- use Symfony\Component\DependencyInjection\Attribute\TaggedIterator;
602
-
603
- class HandlerCollection
604
- {
605
- public function __construct(#[TaggedIterator('app.handler')] iterable $handlers)
606
- {
607
- }
608
- }
609
-
610
607
.. versionadded :: 5.3
611
608
612
609
The ``#[TaggedIterator] `` attribute was introduced in Symfony 5.3 and requires PHP 8.
0 commit comments