Symfony2,重构,一个或多个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;
}
我正在尝试在我的控制器中重构代码。 p>
For 现在,我已经在这个控制器中进行了所有处理,并且我在一个动作中完成了 所以,在一个动作中,我可以有很多 persist() code>,最后只有一个 我现在正在努力清理控制器,并创建函数 在我的所有存储库中减少代码。 p>
但是现在我遇到了一个问题,如果之前有一个动作我是10 我认为它不是 正确的解决方案是增加 我已经找到了一些东西,我想现在,如果有了这段代码,那就有了 每次总是10 flush() code>。 p>
flush() code>。 p>
persist() code>和1 flush() code>,现在我有
10 flush() code>(每个存储库函数一个)。 p>
flush() code>的数量,对吗? p>
flush() code>? 或者只有一个
commit() code>? p>
$ em-> getConnection() - > beginTransaction(); // suspend auto-commit
try {
// ...做一些工作
$ user = new User;
$ user-> setName('George');
$ em-> persist( $ user);
$ em-> flush();
$ em-> getConnection() - > commit();
} catch(Exception $ e){
$ em-> getConnection () - > rollback();
$ em-> close();
抛出$ e;
}
code> pre>
div>
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
.