@@ -511,11 +511,40 @@ 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
+ }
526
+
527
+ Symfony allows you to inject the services using YAML/XML/PHP configuration or
528
+ directly via PHP attributes:
516
529
517
530
.. configuration-block ::
518
531
532
+ .. code-block :: php-attributes
533
+
534
+ // src/HandlerCollection.php
535
+ namespace App;
536
+
537
+ use Symfony\Component\DependencyInjection\Attribute\TaggedIterator;
538
+
539
+ class HandlerCollection
540
+ {
541
+ public function __construct(
542
+ // the attribute must be applied directly to the argument to autowire
543
+ #[TaggedIterator('app.handler')] iterable $handlers
544
+ ) {
545
+ }
546
+ }
547
+
519
548
.. code-block :: yaml
520
549
521
550
# config/services.yaml
@@ -578,24 +607,26 @@ first constructor argument to the ``App\HandlerCollection`` service:
578
607
;
579
608
};
580
609
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
610
If for some reason you need to exclude one or more services when using a tagged
595
611
iterator, add the ``exclude `` option:
596
612
597
613
.. configuration-block ::
598
614
615
+ .. code-block :: php-attributes
616
+
617
+ // src/HandlerCollection.php
618
+ namespace App;
619
+
620
+ use Symfony\Component\DependencyInjection\Attribute\TaggedIterator;
621
+
622
+ class HandlerCollection
623
+ {
624
+ public function __construct(
625
+ #[TaggedIterator('app.handler', exclude: ['App\Handler\Three'])] iterable $handlers
626
+ ) {
627
+ }
628
+ }
629
+
599
630
.. code-block :: yaml
600
631
601
632
# config/services.yaml
0 commit comments