How do I clear the thread in an EntityManager instance of a doctrine shared between different services in symfony2?
I have defined several services in symfony 2 that save changes to the database. These services have a doctrine instance as one of their dependencies:
a.given.service:
class: Acme\TestBundle\Service\AGivenService
arguments: [@doctrine]
If I have two different services and they persist entities via the EntityManager that are derived from a doctrine instance:
$em = $doctrine->getEntityManager();
Will all services always have the same EntityManager? If so, how do I handle flushing if I want to handle all changes in one transaction? I have checked this: http://docs.doctrine-project.org/projects/doctrine-orm/en/2.0.x/reference/transactions-and-concurrency.html and explains how to handle different transactions in the request, but then, what i want to achieve is having different changes to different services being handled as one transaction.
Is there a better approach for handling multiple changes across different services?
For now, it's best to have a front service responsible for calling other services and then cleaning up. Backend services will persist, but will not do flushes.
source to share
The docs you provided are exactly what you want:
$em->getConnection()->beginTransaction();
try{
$service1 = $this->get('myservice1');
$service1->doSomething();
$service2 = $this->get('myservice2');
$service2->doSomething();
$em->getConnection()->commit();
catch(\Exception $e){
$em->getConnection()->rollback();
}
If your $ em is the same as the one in your container i.e. you are only using one entity manager, now you can hide inside your services and roll back if an error occurs.
source to share