Symfony2在控制器方法的服务容器中使用条令

Symfony2在控制器方法的服务容器中使用条令,symfony,doctrine-orm,Symfony,Doctrine Orm,我想在控制器中再次重用代码,因此我创建了一个服务。若我在控制器内部使用该方法,它就工作了,但若该方法由不同的控制器使用,它就不工作了 function testAction() { $em = $this->getDoctrine()->getEntityManager(); $product = $em->getRepository('AcmeStoreBundle:Product')->findAll(); } 如果Different con

我想在控制器中再次重用代码,因此我创建了一个服务。若我在控制器内部使用该方法,它就工作了,但若该方法由不同的控制器使用,它就不工作了

function testAction()
{
      $em = $this->getDoctrine()->getEntityManager();
      $product = $em->getRepository('AcmeStoreBundle:Product')->findAll();
}
如果Different controller使用此代码创建服务,则此代码不起作用

services:
 test:
      class: Acme\BlogBundle\Controller\ClockController
      arguments: 
        entityManager: "@doctrine.orm.entity_manager"
并使用testAction方法将其添加到控制器

use Symfony\Component\DependencyInjection\ContainerAware;
use Doctrine\ORM\EntityManager;
这使我犯了这个错误

Call to a member function has() on a non-object in /var/www/Acme/vendor/symfony
/symfony/src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php on line 191
如果我将控制器方法更改为此

$em = $this->container->get('doctrine.orm.entity_manager');
我明白了

Call to a member function get() on a non-object in..
此召回为$em=$This

如何在服务中正确使用原则

编辑:
已解决

您阅读了吗?依赖项注入是如何工作的?我使用测试方法add services创建了一个类,它很有效,这就是它应该的方式。Symfony是一个有很好文档记录的项目。在食谱中也可以找到一些特别的东西。