JMS DI额外包:如何仅在依赖项存在时注入依赖项


JMS DI Extra Bundle: How do I inject a dependency only if it exists

我使用JMS DI通过注释注入服务:

use JMS'DiExtraBundle'Annotation as DI;
/**
 * @DI'Service("foo.bar.service")
 */
class myClass
{
    /**
    * @DI'Inject("debug.stopwatch")
    * @var $stopWatch 'Symfony'Component'Stopwatch'Stopwatch
    */
    public $stopWatch;
    /**
    * @DI'Inject("serializer")
    * @var $serializer 'JMS'Serializer'Serializer
    */
    public $serializer;
    public function toto()
    {
       if (isset($this->stopwatch)) {
         $this->stopWatch->start("init");
       }
    }
}

但是StopWatch只在Dev环境中可用,所以当在prod中运行时:

The service "foo.bar.service" has a dependency on a non-existent service "debug.stopwatch".' in...

我的问题:如何在我的类中正确地注入stopwatch服务

使依赖项可选:

@DI'Inject("debug.stopwatch", required=false)