我正在研究Symfony的活动。 我希望每次新用户注册时发送电子邮件
我创建了这些类
UserEvent.php
<?php
namespace Acme\UserBundle\Event;
final class UserEvents {
const NEW_USER='new.user';
}
newUserEvent.php
<?php
/**
* EVENT DISPATCHER
*/
namespace Acme\UserBundle\Event;
use Acme\UserBundle\Entity\User;
use Symfony\Component\EventDispatcher\Event;
class NewUserEvent {
protected $user;
public function __construct (User $user) {
$this->user = $user;
}
public function getUser () {
return $this->user;
}
}
newUserListener.php
<?php
namespace Acme\UserBundle\Event;
class NewUserListener {
public function sendEmailToUsers(NewUserEvent $event)
{
// ... send email to users
}
}
在我的控制器中
/**
* @Route("/test",name="test")
*/
public function testEvento(){
$em = $this->getEm();
$dispatcher = new EventDispatcher();
// attach listener
$listner = new NewUserListener();
$dispatcher->addListener(UserEvents::NEW_USER,array($listner,'sendEmailToUsers'));
$user = $em->getRepository('AcmeUserBundle:User')->findOneBy(array('username' => 'alex')); //mock
$event = new NewUserEvent($user);
$dispatcher->dispatch(UserEvents::NEW_USER,$event);
return new Response('hi');
}
但是我得到了这个错误
ContextErrorException:Catchable Fatal Error:参数2传递给 Symfony \ Component \ EventDispatcher \ EventDispatcher :: dispatch()必须是 Symfony \ Component \ EventDispatcher \ Event
的一个实例
我不理解我的错误
答案 0 :(得分:1)
<强> Read this. 强>
class NewUserEvent
必须延长Event
班级(Symfony\Component\EventDispatcher\Event
)event_dispatcher
服务 - $this->get('event_dispatcher')