[英]Should my Service implements transaction & commit method?
Let's say I want to do a bulk User update in my UsersController
. 假设我要在
UsersController
进行批量用户更新。
In my UsersController
I do: 在我的
UsersController
我这样做:
foreach ($users as $user) {
$userService = new UserService();
$user->updateUser($data);
}
If there are a lot of users, it can get slower because the UserService::updateUser method just do a persist()
/ flush()
如果有很多用户,它会变慢,因为UserService :: updateUser方法只是执行
persist()
/ flush()
So I'm wondering if it could be a good idea to do something like that: 所以我想知道这样做是不是一个好主意:
class UserService {
public function setUseTransaction($flag)
{
$this->useTransaction = $flag;
return $this;
}
public function updateUser($data)
{
// some data mapping
$entityManager->persist($user);
if ($this->useTransaction) {
$entityManager->flush();
}
}
public function commit()
{
$entityManager->flush();
}
}
Then in my UsersController
I can do: 然后在我的
UsersController
我可以执行以下操作:
$userService = new UserService();
$userService->setUseTransaction(true);
foreach ($users as $user) {
$userService = new UserService();
$user->updateUser($data);
}
$userService->commit();
What are your thought? 你在想什么
I wouldn't want to expose any transaction-management stuff above my service layer. 我不想在我的服务层之上公开任何事务管理内容。 I'd probably shove all of that stuff down into my service, and expose two public methods updateUser(userEntity) (for a one-off with an implicit flush), and updateUsers(array-of-users) (for batch updates)
我可能会将所有这些东西都推送到了我的服务中,并公开了两个公共方法updateUser(userEntity)(用于一次隐式刷新)和updateUsers(用户数组)(用于批量更新)
Something roughly like: 大致类似于:
class UserService {
public function updateUser(User $user){
$this->_updateUser();
$this->em()->flush();
}
public function updateUsers(array $users){
foreach($users as $u) $this->_updateUser($u);
$this->em()->flush();
}
private function _updateUser(User $user){
//do stuff to $user
$this->em()->persist($user);
}
}
Then, if you later decide you want to chunk your updates into groups of 100, or whatever, all your bulk-update logic is nicely factored in the service, instead of in potentially multiple places in your controller(s). 然后,如果您以后决定将更新分为100个组或其他任何组,则所有批量更新逻辑都会很好地纳入服务中,而不是放在控制器中可能存在的多个位置。
Wrapping it all in a transaction will definitely speed things up. 将所有内容包装在事务中肯定会加快处理速度。
Writing the whole bulk update as a single SQL query will be hundreds of times faster though. 但是,将整个批量更新作为单个SQL查询编写将快数百倍。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.