首页 > 解决方案 > Symfony 3.4 中的依赖注入:检查服务是否存在

问题描述

我正在将应用程序从 Symfony 2.8 迁移到 Symfony 3.4

这些服务现在是私有的,因此我们必须使用依赖注入作为解决方法,而不是直接从容器调用服务。

所以这是以下脚本,我想检查是否存在,然后使用依赖注入调用探查器服务:

<?php

namespace DEL\Bundle\ApiBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Class EstimatePDFController
 *
 * @package DEL\Bundle\ApiBundle\Controller
 */
class EstimateController extends Controller
{
    /**
     *
     * @param Request $request Request object.
     *
     * @return Response A Response instance
     */
    public function sendAction(Request $request)
    {
        // disable debug env outputs
        if ($this->container->has('profiler')) {
            $this->container->get('profiler')->disable();
        }

        return new Response('OK');
    }
}

标签: symfonydependency-injectionsymfony-3.4

解决方案


据我所知,使用自动装配是不可能的。但是文档提供了另一种选择:

  • 添加profiler到你的控制器作为一个属性
  • 添加一个像setProfiler(Profiler $profiler)这样设置属性的设置器
  • 在您的服务定义中添加条件设置器:
    calls:
       - [setProfiler, ['@?profiler']]
    
  • 检查您的方法中是否$this->profiler为空sendAction

推荐阅读