php – 在服务中注入Doctrine实体管理器以实现快速通知程序服务

我是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();
  }
}

这是我在我的bundle中的service.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时,我可以在那里看到我的服务,但没有任何内容持久存储到数据库中.
我不知道我错过了什么,如果你能帮助我,我将不胜感激.

解决方法:

在notifAction中,您从$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();
}        

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...