Saa*_*dia 1 php event-dispatching symfony
这是我有史以来第一次使用创建自定义事件调度程序和订阅者,所以我试图围绕它进行处理,但我似乎无法找出为什么我的自定义事件没有被调度。
我正在关注文档,就我而言,我需要在有人在网站上注册后立即发送事件。
所以在我的内部,我registerAction()正在尝试发送这样的事件
$dispatcher = new EventDispatcher();
$event = new RegistrationEvent($user);
$dispatcher->dispatch(RegistrationEvent::NAME, $event);
Run Code Online (Sandbox Code Playgroud)
这是我的RegistrationEvent课
namespace AppBundle\Event;
use AppBundle\Entity\User;
use Symfony\Component\EventDispatcher\Event;
class RegistrationEvent extends Event
{
const NAME = 'registration.complete';
protected $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function getUser(){
return $this->user;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的RegistrationSubscriber课
namespace AppBundle\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class RegistrationSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array(
KernelEvents::RESPONSE => array(
array('onKernelResponsePre', 10),
array('onKernelResponsePost', -10),
),
RegistrationEvent::NAME => 'onRegistration'
);
}
public function onKernelResponsePre(FilterResponseEvent $event)
{
// ...
}
public function onKernelResponsePost(FilterResponseEvent $event)
{
// ...
}
public function onRegistration(RegistrationEvent $event){
var_dump($event);
die;
}
}
Run Code Online (Sandbox Code Playgroud)
这样做之后,我希望注册过程会在函数处停止,onRegistration但没有发生,然后我查看了分析器的“事件”选项卡,但我也没有看到我的事件列出了它们。
我在这里缺少什么?朝着正确方向的推动将非常受欢迎。
更新:
我想我需要为自定义事件注册一个服务,所以我在里面添加了以下代码services.yml
app.successfull_registration_subscriber:
class: AppBundle\Event\RegistrationSubscriber
arguments: ["@doctrine.orm.entity_manager"]
tags:
- { name: kernel.event_subscriber}
Run Code Online (Sandbox Code Playgroud)
在探查器的事件选项卡中,我确实看到我的自定义事件被列出,但它仍然没有调度。
通过创建自己的EventDispatcher实例,您可以调度其他侦听器永远无法侦听的事件(它们未附加到此调度程序实例)。您需要使用该event_dispatcher服务来通知您使用kernel.event_listener和kernel.event_subscriber标记的所有侦听器:
// ...
class RegistrationController extends Controller
{
public function registerAction()
{
// ...
$this->get('event_dispatcher')->dispatch(RegistrationEvent::NAME, new RegistrationEvent($user););
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3298 次 |
| 最近记录: |