在我的项目中,我希望在RabbitMq上刷新我的对象在刷新后的ID,我该怎么办呢?因为它出现在postPersist中,对象尚未刷新,而在postFlush中,我无法获取对象ID。
public function prePersist(LifecycleEventArgs $args)
{
$object = $args->getObject();
if (!$object instanceof Blast) {
return;
}
$token = $this->tokenGenerator->generateToken();
$object->setName($token);
}
public function postPersist(LifecycleEventArgs $args)
{
$object = $args->getObject();
if (!$object instanceof Blast) {
return;
}
// Publish in Messaging Queue
$this->producer->publish($object->getId());
// Set at last Blast in User session
$this->session->set('last_blast', $object->getId());
}
有人有想法吗?我选择在subescriber中执行此操作,否则,我在刷新后直接在控制器中添加postPersist部分?
答案 0 :(得分:0)
要在Doctrine完成刷新后执行操作,您需要挂钩postFlush
事件。它在刷新过程结束时触发一次,因此不包含任何关联的实体。要解决这个问题,您可以使用postPersist
计划RabbitMQ消息,而不是立即发布,然后“刷新”RabbitMQ消息队列。在代码中它是这样的:
class MessagePublisher
{
private $scheduled = [];
public function postPersist(LifecycleEventArgs $args)
{
$object = $args->getObject();
if (!$object instanceof Blast) {
return;
}
$this->scheduled[] = $object->getId();
}
public function postFlush()
{
foreach ($this->scheduled as $id) {
$this->producer->publish($id);
}
$this->scheduled = [];
}
}