Clément Andraud
Clément Andraud

Reputation: 9279

Symfony2, refactorisation, one or many flush()?

I'm trying to refactor my code in my controller.

For now, i have all treatments in this controller and i finish with a flush() in an action.

So, in an action, i can have many persist() and just one flush() at the end.

I'm working now to clean my controller, and create functions in all my repository to reduce the code.

But now i have a problem, if, before, for an action i was 10 persist() and 1 flush(), now i have 10 flush() (one for each repository-function).

I think it is not a good solution to increase the number of flush() like that, right ?

I have find something and i want to now, if with this code, there is always 10 flush() each time ? Or just one when commit() ?

$em->getConnection()->beginTransaction(); // suspend auto-commit
try {
    //... do some work
    $user = new User;
    $user->setName('George');
    $em->persist($user);
    $em->flush();
    $em->getConnection()->commit();
} catch (Exception $e) {
    $em->getConnection()->rollback();
    $em->close();
    throw $e;
}

Upvotes: 1

Views: 702

Answers (1)

vobence
vobence

Reputation: 523

In your example it's a transaction, which is good if you want to recover your flushed changes if an Exception occurs. In transactions the commit() will actually save your work, and the rollback() will revert the changes.

In general situation you should avoid too much flush() as wll, because it's consume your resources, and there will be a lot unnecessary database action. I think the repository is mainly for finding querys and not for "flushing" querys. If you want to do every "flush query" in repository, you may want to persist the classes in your repostory and at the end of your controller you can flush the EntityManager.

Upvotes: 1

Related Questions