ZF2 条令服务 - 多次调用
ZF2 Doctrine Service - Multiple calls
我已经为我的应用程序设置了日记服务。我的想法是将服务注入我的控制器(通过工厂),然后根据需要调用 diaryEntry 方法将日记条目存储到 dB 中。我遇到的问题是,如果我在控制器操作中多次调用该方法,我只会获取存储在 dB 中的最后一个条目。这里是 DiaryService::diaryEntry -
public function diaryEntry($projectUrn, $msg, $diaryCategory = 14)
{
$em = $this->em;
$user = $this->user;
$ProjectDiary = $this->projectDiaryEntity;
if(is_numeric($projectUrn)) {
$projectUrn = $em->find('Application\Entity\ProjectUrn', $projectUrn);
}
$ProjectDiary->setProjectUrn($projectUrn);
$ProjectDiary->setDiaryCategory($em->find('Application\Entity\DiaryCategory', $diaryCategory));
$ProjectDiary->setStatus(1);
$ProjectDiary->setComment($msg);
$ProjectDiary->setUser($em->getRepository('Application\Entity\Users')->findOneBy(['username' => $user->username]));
$ProjectDiary->setTimestamp(new \DateTime());
$em->persist($ProjectDiary);
$em->flush();
return;
}
在控制器动作中我有这样的东西:
$this->diaryService->diaryEntry($order->getProjectUrn(), 'test msg 1);
$this->diaryService->diaryEntry($order->getProjectUrn(), 'test msg 2);
问题是只有消息 2 被保存在 dB 中,消息 1 没有被保存。最后的更新是在 diaryEntry 方法的末尾添加刷新,但这并没有什么不同。有谁知道我可以从哪里着手解决这个问题?它是糟糕的架构,也许不适合作为服务,应该利用其他东西吗?
我很乐意粘贴应用程序所需的任何其他代码
提前感谢您的帮助
如果你post关于如何初始化$this->projectDiaryEntity
的信息会更有帮助,但我敢打赌你通过工厂注入日记实体对象,所以你所有的操作都是在同一个对象上完成的。
尝试用这行替换你的行:
$ProjectDiary = clone $this->projectDiaryEntity;
你的方法看起来不太好,但是很难根据一种方法的几行代码来判断你应该改变什么。
如果您的默认 status
是 1
,您可以在您的实体 class 中设置它。时间戳也是如此。
我已经为我的应用程序设置了日记服务。我的想法是将服务注入我的控制器(通过工厂),然后根据需要调用 diaryEntry 方法将日记条目存储到 dB 中。我遇到的问题是,如果我在控制器操作中多次调用该方法,我只会获取存储在 dB 中的最后一个条目。这里是 DiaryService::diaryEntry -
public function diaryEntry($projectUrn, $msg, $diaryCategory = 14)
{
$em = $this->em;
$user = $this->user;
$ProjectDiary = $this->projectDiaryEntity;
if(is_numeric($projectUrn)) {
$projectUrn = $em->find('Application\Entity\ProjectUrn', $projectUrn);
}
$ProjectDiary->setProjectUrn($projectUrn);
$ProjectDiary->setDiaryCategory($em->find('Application\Entity\DiaryCategory', $diaryCategory));
$ProjectDiary->setStatus(1);
$ProjectDiary->setComment($msg);
$ProjectDiary->setUser($em->getRepository('Application\Entity\Users')->findOneBy(['username' => $user->username]));
$ProjectDiary->setTimestamp(new \DateTime());
$em->persist($ProjectDiary);
$em->flush();
return;
}
在控制器动作中我有这样的东西:
$this->diaryService->diaryEntry($order->getProjectUrn(), 'test msg 1);
$this->diaryService->diaryEntry($order->getProjectUrn(), 'test msg 2);
问题是只有消息 2 被保存在 dB 中,消息 1 没有被保存。最后的更新是在 diaryEntry 方法的末尾添加刷新,但这并没有什么不同。有谁知道我可以从哪里着手解决这个问题?它是糟糕的架构,也许不适合作为服务,应该利用其他东西吗?
我很乐意粘贴应用程序所需的任何其他代码
提前感谢您的帮助
如果你post关于如何初始化$this->projectDiaryEntity
的信息会更有帮助,但我敢打赌你通过工厂注入日记实体对象,所以你所有的操作都是在同一个对象上完成的。
尝试用这行替换你的行:
$ProjectDiary = clone $this->projectDiaryEntity;
你的方法看起来不太好,但是很难根据一种方法的几行代码来判断你应该改变什么。
如果您的默认 status
是 1
,您可以在您的实体 class 中设置它。时间戳也是如此。