Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2.3 Better way to get EntityManager inside a Controller

I'm using Symfony2.3 and I currently using EntityManager as shown inside __construct()

Which its a better aproach using EntityManager from __construct() or using inside each method ? as shown in public indexAction()

/**
 * QuazBar controller.
 *
 */
class QuazBarController extends Controller
{

    public function __construct()
    {
        $this->em = $GLOBALS['kernel']->getContainer()->get('doctrine')->getManager();
    }

    /**
     * Lists all QuazBar entities.
     *
     */
    public function indexAction(Request $request)
    {
        $session    = $request->getSession();
        $pagina     = $request->query->get('page', 1);
        $em         = $this->getDoctrine()->getManager();
    }
like image 691
NBPalomino Avatar asked Mar 03 '14 18:03

NBPalomino


1 Answers

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.

like image 69
Onema Avatar answered Nov 15 '22 05:11

Onema