If you must have the EntityManager
available in your constructor, a good way to get it is injecting it to the constructor.
To do this you must define your controller as a service.
# src/Acme/DemoBundle/Resources/config/services.yml
parameters:
# ...
acme.controller.quazbar.class: Acme\DemoBundle\Controller\QuazBarController
services:
acme.quazbar.controller:
class: "%acme.controller.quazbar.class%"
# inject doctrine to the constructor as an argument
arguments: [ @doctrine.orm.entity_manager ]
Now all you have to do is modify your controller:
use Doctrine\ORM\EntityManager;
/**
* QuazBar controller.
*
*/
class QuazBarController extends Controller
{
public function __construct(EntityManager $em)
{
$this->em = $em;
}
// ...
}
If you do not require the Entity Manager
in the constructor, you can simply get it using the Dependency Injection Container from any method in your controller:
$this->getDoctrine()->getManager();
OR
$this->container->get('doctrine')->getManager();
Controller/setter injection is a good choice because you are not coupling your controller implementation to the DI Container.
At the end which one you use is up to your needs.