问题描述
我正在将应用程序从Symfony 2.8迁移到Symfony 3.4
这些服务现在是私有的,因此,必须使用依赖项注入作为解决方法,而不是从容器中直接调用这些服务。
所以这是以下脚本,我想检查是否存在,然后使用依赖注入调用 profiler 服务:
<?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');
}
}
解决方法
据我所知,使用自动装配是不可能的。但是documentation提供了另一种选择:
- 将
profiler
作为属性添加到您的控制器 - 添加类似
setProfiler(Profiler $profiler)
的设置器来设置属性 - 在您的服务定义中添加条件设置器:
calls: - [setProfiler,['@?profiler']]
- 在您的
$this->profiler
方法中检查sendAction
是否为空
检查是否存在意味着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会失败。