I like the general idea of passing Doctrine repositories as services in Symfony2 and avoiding passing EntityManager. However, while it's fine when reading data, the saving logic becomes a bit problematic here.
Let's take this as a reference: http://php-and-symfony.matthiasnoback.nl/2014/05/inject-a-repository-instead-of-an-entity-manager/, but with a change separating persisting and flushing:
class DoctrineORMCustomerRepository extends EntityRepository implements CustomerRepository
{
public function persist(Customer $customer)
{
$this->_em->persist($customer);
}
public function flush()
{
$this->_em->flush();
}
}
The problem is you flush in a particular repository all changes in all entities.
Now, is it possible to flush just one class of entities? (possibly cascading to dependent entities), so I could basically do something like:
foreach ($customers as $customer) {
$this->customerRepository->persist($customer);
}
$this->customerRepository->flush();
I considered something like:
$this->_em->flush(getUnitOfWork()->getIdentityMap()[$this->_entityName]);
But I must have misunderstood something, because it doesn't work.
EDIT: Yes, I'm aware I can do $this->_em->flush($entity)
, but doing this one by one is suboptimal. I even know I can do $this->_em->flush($arrayOfEntities)
, but to make the "foreach" example work this way I'd have to keep track of all the persisted entities in the repository duplicating some Doctrine internals.
Try this:
$em->flush($entity);
Then doctrine only will flush $entity, ignoring any other.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With