Как ввести услугу в другую службу в Symfony?
Я пытаюсь использовать службу ведения журналов в другой службе, чтобы избавиться от этой службы.
My 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]] ]
Это отлично работает в контроллерах и т.д., но я не получаю его, когда использую его в других сервисах.
Любые советы?
Ответы
Ответ 1
Вы передаете служебный идентификатор в качестве аргумента конструктору или настройщику службы.
Предполагая, что ваша другая служба - userbundle_service
:
userbundle_service:
class: Main\UserBundle\Controller\UserBundleService
arguments: [@security.context, @logger]
Теперь Logger передается в конструктор UserBundleService
если вы его правильно обновляете, eG
protected $securityContext;
protected $logger;
public function __construct(SecurityContextInterface $securityContext, Logger $logger)
{
$this->securityContext = $securityContext;
$this->logger = $logger;
}
Ответ 2
Для Symfony 3.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!
Для более старых версий Symfony, где autowiring не существует -
// services.yml
services:
\AppBundle\Services\MainService:
arguments: ['@injectedService']
Ответ 3
Вы можете использовать контейнер в своей службе:
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();
}