在DI中有自动装配,注释定义和PHP定义。
在Symfony 3.3中,默认情况下启用自动装配。因此,如果我禁用自动装配,我可以使用注释来定义服务吗?
class Foo
{
/**
* @Inject({"my.specific.service"})
*/
public function __construct(Bar $param1)
{
}
}
更新:使用JMSDiExtraBundle
namespace MediaBundle\Net;
use JMS\DiExtraBundle\Annotation\Inject;
use JMS\DiExtraBundle\Annotation\InjectParams;
use JMS\DiExtraBundle\Annotation\Service;
/**
* @Service("some.service.id", public=false, environments = {"prod", "test", "dev"})
*/
class Foo
{
private $em;
private $session;
/**
* @InjectParams({
* "em" = @Inject("doctrine.orm.entity_manager"),
* "session" = @Inject("session")
* })
*/
public function __construct($em, $session)
{
$this->em = $em;
$this->session = $session;
}
}
在控制器中调用服务:
namespace MediaBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class DefaultController extends Controller
{
/**
* @Route("/media")
*/
public function indexAction()
{
$someService = $this->get('some.service.id');
return $this->render('MediaBundle:Default:index.html.twig');
}
}
结果:You have requested a non-existent service "some.service.id".
答案 0 :(得分:2)
您的服务是否在某处注入?如果没有,则会因public=false
而从容器中删除,请参阅http://symfony.com/blog/new-in-symfony-3-2-improved-private-services