在消息被持久化之前,消息元数据不存在。这就是为什么您必须在将消息保存到数据库后设置读取状态。
最简单的方法是注册 EventSubscriber。工作示例代码:
<?php
namespace Acme\DemoBundle\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use FOS\MessageBundle\Event\MessageEvent;
use FOS\MessageBundle\Event\FOSMessageEvents as Event;
use FOS\MessageBundle\ModelManager\MessageManagerInterface;
class MessageSendSubscriber implements EventSubscriberInterface
{
private $messageManager;
public function __construct(MessageManagerInterface $messageManager)
{
$this->messageManager = $messageManager;
}
public static function getSubscribedEvents()
{
return array(
Event::POST_SEND => 'markAsReadBySender'
);
}
public function markAsReadBySender(MessageEvent $event)
{
$message = $event->getMessage();
$sender = $message->getSender();
$this->messageManager->markAsReadByParticipant($message, $sender);
$this->messageManager->saveMessage($message);
}
}
在 services.yml 中:
message_send_listener:
class: Acme\DemoBundle\EventListener\MessageSendSubscriber
arguments: [@fos_message.message_manager]
tags:
- { name: kernel.event_subscriber }
在这里您可以查看可以订阅哪些事件:
https ://github.com/FriendsOfSymfony/FOSMessageBundle/blob/master/Event/FOSMessageEvents.php