微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决Symfony 3.4中的依赖注入:检查服务是否存在

我正在将应用程序从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会失败。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。