Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine: Can I flush only one class of entities?

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.

like image 764
Kalmar Avatar asked Nov 18 '16 16:11

Kalmar


1 Answers

Try this:

$em->flush($entity);

Then doctrine only will flush $entity, ignoring any other.

like image 82
CStff Avatar answered Sep 28 '22 23:09

CStff