简体   繁体   English

Symfony2,重构,一个或多个flush()?

[英]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. 现在,我已经在此控制器中进行了所有处理,并且在操作中以flush()完成了操作。

So, in an action, i can have many persist() and just one flush() at the end. 因此,在一个动作中,我可以有很多persist() ,最后只有一个flush()

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). 但是现在我有一个问题,如果在以前,对于一个动作,我是persist()和1 flush() ,现在我有10 flush() (每个存储库功能一个)。

I think it is not a good solution to increase the number of flush() like that, right ? 我认为这样增加flush()的数量不是一个好的解决方案,对吗?

I have find something and i want to now, if with this code, there is always 10 flush() each time ? 我找到了一些东西,现在我想要,如果使用此代码,每次总是有10 flush()吗? Or just one when commit() ? 还是当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;
}

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. 在事务中, commit()实际上将保存您的工作,而rollback()将还原更改。

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. 在一般情况下,您应该避免像wll那样使用flush()太多,因为它会消耗您的资源,并且会有很多不必要的数据库操作。 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 . 如果要对存储库中的每个“刷新查询”进行操作,则可能希望将类保留在您的重新发布记录中,并且在控制器的末尾,您可以刷新EntityManager

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM