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