简体   繁体   中英

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. 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(). 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. But this container is injected AFTER your object construction thanks to the 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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