symfony - 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');
}
}
解决方案
据我所知,使用自动装配是不可能的。但是文档提供了另一种选择:
- 添加
profiler
到你的控制器作为一个属性 - 添加一个像
setProfiler(Profiler $profiler)
这样设置属性的设置器 - 在您的服务定义中添加条件设置器:
calls: - [setProfiler, ['@?profiler']]
- 检查您的方法中是否
$this->profiler
为空sendAction
推荐阅读
- mysql - SQL、主键、外键和表
- ios - 有没有办法在 SwiftUI 中制作 List 样式 insetGrouped?
- react-native - 需要升级现有项目的RN版本
- c# - LINQ中的内部连接后如何将相同的结果组合成一行
- python - 在游戏设计中,我们是否必须在每一帧中重新绘制整个窗口?
- django - Docker:从 Web 容器内部执行 django 迁移到 db 容器
- python - Visual Studio 16.3.4 + Python Tools 16.3 交互式窗口中断调试
- php - 如何在 laravel 6 中安装 brozot/Laravel-FCM?
- sql - SQL SERVER:当数据包含空值时如何选择数据
- authentication - 身份验证和授权 - HTTP 请求正文中的令牌