How to call Entity Manager in a constructor?
You need to make a service for your class and pass the doctrine entity manager as the argument doctrine.orm.entity_manager
.Like in services.yml
services: test.cutom.service: class: Test\YourBundleName\Yourfoldernameinbundle\Test #arguments: arguments: [ @doctrine.orm.entity_manager ] #entityManager: "@doctrine.orm.entity_manager"
You must import your services.yml in config.yml
imports: - { resource: "@TestYourBundleName/Resources/config/services.yml" }
Then in your class's constructor get entity manager as argument
use Doctrine\ORM\EntityManager;Class Test { protected $em; public function __construct(EntityManager $entityManager) { $this->em = $entityManager; }}
Hope this makes sense
Don't extend the base controller class when you register controller as a service. There is a documentation about it here
class ImageTestController{ private $em; public function __construct(EntityManager $em) { $this->em = $em; } public function someAction() { // do something with $this->em }}// services.ymlservices: acme.controller.image_test: class: Acme\SomeBundle\Controller\ImageTestController// routing.ymlacme: path: / defaults: { _controller: acme.controller.image_test:someAction }
Why do you want to grab the Doctrine 2 EntityManager in the constructor of a controller?
Why not simply do $em = $this->getDoctrine()->getManager();
(or $em = $this->getDoctrine()->getEntityManager();
in Symfony 2.0) in the action(s) you need it? This saves you from the overhead of initializing the EntityManager when you don't need it.
If you really do want to do this, there are clear instructions on How to define Controllers as Services. Basically it looks like this:
# src/MSD/HomeBundle/Controller/ImageTransController.phpnamespace MSD\HomeBundle\Controller;use Doctrine\ORM\EntityManager;class ImageTransController{ private $em; public function __construct(EntityManager $em) { $this->em = $em; } public function indexAction() { // use $this->em }}# src/MSD/HomeBundle/Resources/config/services.ymlparameters: msd.controller.image_trans.class: MSD\HomeBundle\Controller\ImageTransControllerservices: msd.controller.image_trans: class: "%msd.controller.image_trans.class%" arguments: ["@doctrine.orm.default_entity_manager"]# app/config/routing.ymlmsd_home_cambiardimensiones: path: /cambiardimensiones defaults: { _controller: msd.controller.image_trans:indexAction }