在服务中注入Doctrine实体管理器,以实现快速通知服务


Injecting Doctrine entity manager in service in order to implement a quick notifier service

我是symfony 2的新手,通过文档,我正在努力创建一个通知服务来通知用户列表有关一些更新(用户实体与通知实体在OneToMany关系上,只是为了弄清楚)

这是服务类:

<?php
namespace OC'UserBundle'Services;
use  OC'UserBundle'Entity'Notification;
use  Doctrine'ORM'EntityManager as EntityManager;
class Notificateur
{
    protected $em;
    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }
    public function notifier($text, $users)
  {
      foreach ($users as $user)
      {
          $notification=new Notification();
          $notification->setDate(new 'DateTime());
          $notification->setText($text);
          $notification->setStatus('1');
          $notification->setUser($user);
          $this->em->persist($notification);
      }
          $this->em->flush();
  }
}

这就是我在service中定义服务的方式。my bundle中的Yml:

services
    notificateur:
        class: OC'UserBundle'Services'Notificateur
        arguments: [ @doctrine.orm.entity_manager ]

,这是我的控制器内的动作(这是仅用于测试,通知当前用户:

public function notifAction() {
        $user=$this->getUser();
        $notificateur=$this->get('notificateur');
        $notificateur->notifier('your account is updated',$user);
        Return new Response('OK');
    }

当我执行app/console debug:container时,我可以看到我的服务在那里,但没有任何东西持久化到数据库。我不知道我错过了什么,如果你能帮助我,我会很感激的。

从$this->getUser()传递单个用户

$notificateur->notifier('your account is updated',$user);

在您的服务中,您正在遍历用户数组,而不是单个用户。如果您只想处理单个用户,可以这样做:

public function notifier($text, $user) {
    $notification=new Notification();
    $notification->setDate(new 'DateTime());
    $notification->setText($text);
    $notification->setStatus('1');
    $notification->setUser($user);
    $this->em->persist($notification);
    $this->em->flush();
}        

解决了。这是一个php问题,

我在notififier()函数中创建了一个数组,并将当前用户添加到其中:

public function notifAction() {
        $user=$this->getUser();
        $users = array();
        array_push($users, $user);
        $notificateur=$this->get('notificateur');
        $notificateur->notifier('your account is updated',$users);
        Return new Response('OK');
}

这只是为了测试它是否有效,但主要目标是获取事件的订阅成员列表并通知所有成员,然后是以下几行:

$user=$this->getUser();
$users = array();
array_push($users, $user);

将被替换为

$repository = $this->getDoctrine()
->getRepository(.....)
$list_users=$repository->find(....)
//
//
//
$notificateur=$this->get('notificateur');
$notificateur->notifier('your account is updated',$list_users);
Return new Response('OK');

希望这对那些需要使用symfony 2实现快速通知系统的人有所帮助。