如何在Symfony的另一个服务中注入服务?

时间:2012-08-03 18:45:17

标签: php 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]] ]

这在控制器等方面运行良好。但是当我在其他服务中使用它时,我没有得到任何结果。

任何提示?

3 个答案:

答案 0 :(得分:35)

将服务id作为参数传递给服务的构造函数或setter。

假设您的其他服务是userbundle_service

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

现在Logger传递给UserBundleService构造函数,只要你正确更新它,例如

protected $securityContext;
protected $logger;

public function __construct(SecurityContextInterface $securityContext, Logger $logger)
{
    $this->securityContext = $securityContext;
    $this->logger = $logger;
}

答案 1 :(得分:4)

对于Symfony 3.3及更高版本,最简单的解决方案是使用依赖注入

您可以直接将服务注入其他服务(例如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();
}

中提琴!您可以访问注入服务的任何功能!

对于不存在自动装配的旧版Symfony -

// services.yml
services:
    \AppBundle\Services\MainService:
        arguments: ['@injectedService']

答案 2 :(得分:-4)

您可以在服务中使用容器:

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();

}