4

当我创建线程时,如何设置线程的创建者读取消息?

我有这部分代码

$composer = $this->get('fos_message.composer');
    $message  = $composer->newThread()
        ->setSender($this->getUser())
        ->setSubject('myThread')
        ->setBody($request->get('createThread')['my_thread']);

    $sender = $this->get('fos_message.sender');
    $sender->send($message);

但是当我在最后一行发送消息时,在数据库中 is_read 的值设置为 0,而发送者应该设置为 1。所以,我需要将作者设置为在发送消息时被读取。

任何人?:)

4

1 回答 1

6

在消息被持久化之前,消息元数据不存在。这就是为什么您必须在将消息保存到数据库后设置读取状态。

最简单的方法是注册 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

于 2013-06-25T09:21:19.727 回答