假设我想在我的UsersController
.
在我的UsersController
我做:
foreach ($users as $user) {
$userService = new UserService();
$user->updateUser($data);
}
如果有很多用户,它可能会变慢,因为 UserService::updateUser 方法只是执行persist()
/flush()
所以我想知道做这样的事情是否是个好主意:
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();
}
}
然后在我的UsersController
我可以做:
$userService = new UserService();
$userService->setUseTransaction(true);
foreach ($users as $user) {
$userService = new UserService();
$user->updateUser($data);
}
$userService->commit();
你有什么想法?