I'm using Doctrine 2, and would like this ORM to auto flush()
the EntityManager before executing any SELECT
query, to ensure consistency at all times within the application (this application is abstracting a lot, and should not have any knowledge of the EntityManager, apart from inside the Repositories).
Is there an option to do that with Doctrine?
If not, any strategy to implement this easily?
The only solution I've found so far, is to manually flush()
before issuing a SELECT
query in the repository methods that must not return stale data:
class OrderRepository
{
public function findByUser(User $user)
{
$this->em->flush();
$query = $this->em->createQuery( ... );
// ...
}
}
This way, the flush is hidden from the services that consume the repositories.
Why do you need to flush (write changes) before all selects? Is it possible that you require transactional consistency? ie, will an insert / update be dependent on the results of a previous select? In which case i'd suggest using an explicit transaction, like so:
$em->transactional(function($em) {
$entity = $em->find('Entity', 123);
if ($entity->getValue() > 2)
{
$user = new User;
$user->setName('George');
$em->persist($user);
}
});
If not, i'd suggest sticking with the default set up and let the unitOfWork stack up and optimise insertions / updates toward the end of your runtime.