@@ -368,3 +368,46 @@ Now you can use the service locator by injecting it in any other service:
368368 better to create and inject it as an anonymous service.
369369
370370.. _`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__ ``::
385+
386+ // src/Service/MyService.php
387+ namespace App\Service;
388+
389+ use Psr\Log\LoggerInterface;
390+ use Symfony\Component\DependencyInjection\ServiceSubscriberInterface;
391+ use Symfony\Component\DependencyInjection\ServiceSubscriberTrait;
392+ use Symfony\Component\Routing\RouterInterface;
393+
394+ class MyService implements ServiceSubscriberInterface
395+ {
396+ use ServiceSubscriberTrait;
397+
398+ public function doSomething()
399+ {
400+ // $this->router() ...
401+ // $this->logger() ...
402+ }
403+
404+ private function router(): RouterInterface
405+ {
406+ return $this->container->get(__METHOD__);
407+ }
408+
409+ private function logger(): LoggerInterface
410+ {
411+ return $this->container->get(__METHOD__);
412+ }
413+ }
0 commit comments