Access to database in a listener in Symfony 2 Access to database in a listener in Symfony 2 symfony symfony

Access to database in a listener in Symfony 2


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


If your use case allows you to use a Doctrine Event Listener directely

#services.ymlqis.listener.contractBundleStatusListener:    class: Acme\AppBundle\EventListener\MyListener    tags:        - { name: doctrine.event_listener, event: postPersist }

you can get the Entity Manager from the LifecycleEventArgs:

<?phpuse Doctrine\ORM\Event\LifecycleEventArgs;class MyListener{    public function postPersist(LifecycleEventArgs $args)    {        $entity = $args->getEntity();        if ($entity instanceof Foo) {            $entityManager = $args->getEntityManager();            $entityManager->persist($entity);            $entityManager->flush();        }    }}


It seems like you're injecting the service container into the listener, so you can access Doctrine this way:

$doctrine = $this->container->get('doctrine');