@@ -368,3 +368,47 @@ Now you can use the service locator by injecting it in any other service:
368
368
better to create and inject it as an anonymous service.
369
369
370
370
.. _`Command pattern` : https://en.wikipedia.org/wiki/Command_pattern
371
+
372
+ Service Subscriber Trait
373
+ ------------------------
374
+
375
+ .. versionadded :: 4.2
376
+ The :class: `Symfony\\ Component\\ DependencyInjection\\ ServiceSubscriberTrait `
377
+ was introduced in Symfony 4.2.
378
+
379
+ The :class: `Symfony\\ Component\\ DependencyInjection\\ ServiceSubscriberTrait `
380
+ provides an implementation for
381
+ :class: `Symfony\\ Component\\ DependencyInjection\\ ServiceSubscriberInterface `
382
+ that looks through all methods in your class that have no arguments and a return
383
+ type. It provides a ``ServiceLocator `` for the services of those return types.
384
+ The service id is ``__METHOD__ ``. This allows you to easily add dependencies
385
+ to your services based on type-hinted helper methods::
386
+
387
+ // src/Service/MyService.php
388
+ namespace App\Service;
389
+
390
+ use Psr\Log\LoggerInterface;
391
+ use Symfony\Component\DependencyInjection\ServiceSubscriberInterface;
392
+ use Symfony\Component\DependencyInjection\ServiceSubscriberTrait;
393
+ use Symfony\Component\Routing\RouterInterface;
394
+
395
+ class MyService implements ServiceSubscriberInterface
396
+ {
397
+ use ServiceSubscriberTrait;
398
+
399
+ public function doSomething()
400
+ {
401
+ // $this->router() ...
402
+ // $this->logger() ...
403
+ }
404
+
405
+ private function router(): RouterInterface
406
+ {
407
+ return $this->container->get(__METHOD__);
408
+ }
409
+
410
+ private function logger(): LoggerInterface
411
+ {
412
+ return $this->container->get(__METHOD__);
413
+ }
414
+ }
0 commit comments