How to create custom event in symfony2

匿名 (未验证) 提交于 2019-12-03 00:53:01

问题:

I want to create custom events called user_logged so that i can attach my listeners to those events.

I want to execute few functions whenever user has logged in.

回答1:

Create a class which extends Symfony\Component\EventDispatcher\Event.

Then, use the event dispatcher service to dispatch the event:

$eventDispatcher = $container->get('event_dispatcher'); $eventDispatcher->dispatch('custom.event.identifier', $event);

You can register your event listener service like so:

tags:     - { name: kernel.event_listener, event: custom.event.identifier, method: onCustomEvent }


回答2:

This answer is little bit extend answer.

services.yml

custom.event.home_page_event:     class: AppBundle\EventSubscriber\HomePageEventSubscriber     tags:         - { name: kernel.event_listener, event: custom.event.home_page_event, method: onCustomEvent }

AppBundle/EventSubscriber/HomePageEventSubscriber.php

namespace AppBundle\EventSubscriber; class HomePageEventSubscriber {     public function onCustomEvent($event)     {         var_dump($event->getCode());     } }

AppBundle/Event/HomePageEvent.php

namespace AppBundle\Event; use Symfony\Component\EventDispatcher\Event; class HomePageEvent extends Event {     private $code;      public function setCode($code)     {         $this->code = $code;     }      public function getCode()     {         return $this->code;     } }

anywhere you wish, for example in home page controller

    use AppBundle\Event\HomePageEvent;     // ...     $eventDispatcher = $this->get('event_dispatcher');     $event = new HomePageEvent();     $event->setCode(200);     $eventDispatcher->dispatch('custom.event.home_page_event', $event);


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!