Alex Rivera | Logout

Access to database in a listener in Symfony 2

Asked 2012-01-11T17:12:34.047
10

We need to access to database info in a listener. We configure the listener in a service.yml The listener is like:

namespace company\MyBundle\Listener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class RequestListener
{
    protected $container;

public function __construct(ContainerInterface $container)
{
    $this->container = $container;
}

public function onKernelRequest(GetResponseEvent $event)
{
...

How can we access to doctrine at onKernelRequest function?

I tried to extends from controller and do:

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

and it works but I think this is a bad practice.

Edit
Report

1 Answer

31

You can just inject the service container. First change the constructor to get an EntityManager:

use Doctrine\ORM\EntityManager;

class RequestListener {
    protected $em;
    function __construct(EntityManager $em)
    {
        $this->em = $em;
    }
    //...
}

And next configure your service:

#...
services:
    foo.requestlistener:
        class: %foo.requestlistener.class%
        arguments:
            - @doctrine.orm.entity_manager
answered 2012-01-11T19:03:50.960

Your Answer