문제

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();
    }
도움이 되었습니까?

해결책

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.

다른 팁

In symfony 2.3, I believe that a connection to the doctrine entity manager is built into the controller class.

$em = $this->getDoctrine()->getManager();

Best practice is to make this call in the controllers when you need it. If it's simply convenience, you could derive a controller class and add something like getEm() if you find that too odious.

Often, your own controller class is a good idea, for baking in security restrictions and making your code more DRY.

Can we define a constructor in the controller class ? The doctrine is a service. Does it make any difference to get doctrine in constructor or to get wherever you want want it from di. Both ways you get the same service. Why do you want to inject the em that is already injected.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top