简体   繁体   English

控制器构造函数Symfony2中的实体管理器

[英]Entity manager in Controller Constructor Symfony2

I am writing a simple symfony2 application and I wanted to create a constructor for my Default Controller and have it run a query with doctrine. 我正在编写一个简单的symfony2应用程序,我想为我的Default Controller创建一个构造函数,并让它运行带有主义的查询。 So I wrote something like: 所以我写了类似的东西:

public function __construct()
{
  $product = $this->getDoctrine()
    ->getRepository('AcmeStoreBundle:Product')
    ->find($id);

  DefaultController::$products = $product;
}

The problem is that it says that there is a call to an undefined method on get(). 问题在于它说有对get()上未定义方法的调用。 What am I missing? 我想念什么?

It could be a matter of dependency injection (DI) => You are in the constructor of the controller, and try to get the Doctrine object from your container. 这可能是依赖注入(DI)=>的问题,您在控制器的构造函数中,并尝试从容器中获取Doctrine对象。 But this container is injected AFTER your object construction thanks to the DI. 但是,借助DI,此容器将在您的对象构造之后注入。

So when you try to do the following : 因此,当您尝试执行以下操作时:

$this->getDoctrine()...

it's quite normal that you don't have the methods on your container, because it doesn't exist yet in your controller. 在容器上没有方法是很正常的,因为它在控制器中尚不存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM