如何为Symfony2控制器实现基类

sto*_*fln 6 dependency-injection symfony

有一些文章涉及到这个主题,但它们似乎都不是一个实用的解决方案.我的目标是将一些基本方法(无论如何我需要在每个控制器中)放入基本控制器,例如

   $this->getEntityManager();
   $this->getRequest();
   $this->getRepository($entityName);
Run Code Online (Sandbox Code Playgroud)

如何才能做到这一点?

AFAIK我们必须将服务注入到basecontroller中,但是如何告诉类为其超类使用服务?有一些关于控制器和依赖注入的好文章[1],但最后我也陷入了这种方法,请看我的评论:[2]

[1] http://miller.limethinking.co.uk/2011/04/15/symfony2-controller-as-service/

[2] http://miller.limethinking.co.uk/2011/04/15/symfony2-controller-as-service/#comment-579

Koc*_*Koc 3

伪代码

MyBaseController impliments Symfony\Component\Di\ContainerAwareInterface
  setContainer($container)
    $this->container = $container

  getEntityManager
    return $this->container->get('doctrine.orm.entity_manager')
Run Code Online (Sandbox Code Playgroud)