Symfony 3.4中的依赖项注入:检查服务的存在



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

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

因此,这是下面的脚本,我想检查是否存在,然后使用依赖注入调用profiler服务:

<?php
namespace DELBundleApiBundleController;
use SymfonyBundleFrameworkBundleControllerController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
/**
* Class EstimatePDFController
*
* @package DELBundleApiBundleController
*/
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');
}
}

据我所知,使用自动布线是不可能的。但文件提供了一个替代方案:

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

检查是否存在意味着Profiler在使用之前已经存在,对吗?因此,您可以使用默认值自动连接Profiler,如果它不为null,则它存在。类似这样的东西:

/**
* @param Request  $request  Request object.
* @param Profiler $profiler The Profiler if the service exists 
*
* @return Response A Response instance
*/
public function sendAction(Request $request, Profiler $profiler = null): Response
{
// disable debug env outputs
if ($profiler !== null) {
$profiler->disable();
}
return new Response('OK');
}

顺便说一下,这是默认行为。它试图解析这个参数,但如果失败,它就会跳过它。如果没有默认值,那么PHP就会失败。

最新更新