Как ввести услугу в другую службу в Symfony?

Я пытаюсь использовать службу каротажа в другой службе, чтобы избавиться от этой услуги.

Мой config.yml выглядит так:

services: userbundle_service: class: Main\UserBundle\Controller\UserBundleService arguments: [@security.context] log_handler: class: %monolog.handler.stream.class% arguments: [ %kernel.logs_dir%/%kernel.environment%.jini.log ] logger: class: %monolog.logger.class% arguments: [ jini ] calls: [ [pushHandler, [@log_handler]] ] 

Это отлично работает в контроллерах и т. Д., Но я не получаю, когда использую его в других сервисах.

Какие-нибудь советы?

Вы передаете служебный идентификатор в качестве аргумента конструктору или настройщику службы.

Предполагая, что ваша другая служба – userbundle_service :

 userbundle_service: class: Main\UserBundle\Controller\UserBundleService arguments: [@security.context, @logger] 

Теперь Logger передается в конструктор UserBundleService если вы его правильно обновите.

Для Symfony 3 и выше самым простым решением является использование Injection Dependency Injection

Вы можете напрямую вводить услугу в другую услугу (например, MainService )

 // AppBundle/Services/MainService.php // 'serviceName' is the service we want to inject public function __construct(\AppBundle\Services\serviceName $injectedService) { $this->injectedService = $injectedService; } 

Затем просто используйте введенную службу любым способом MainService как

 // AppBundle/Services/MainService.php public function mainServiceMethod() { $this->injectedService->doSomething(); } 

И альт! Вы можете получить доступ к любой функции Injected Service!

Вы можете использовать контейнер в своей службе:

 userbundle_service: class: Main\UserBundle\Controller\UserBundleService arguments: [@security.context] 

В вашем сервисе:

 use Symfony\Component\DependencyInjection\ContainerInterface; class UserBundleService { /** * @var ContainerInterface */ private $_container; public function __construct(ContainerInterface $_container) { $this->_container = $_container; } $var = $this->_container->get('logger'); $var->functionLoggerService(); }