40

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.

2 Answers 2

78

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 }
5
  • 6
    Good answer. In addition, there are more details here: symfony.com/doc/current/components/event_dispatcher/…
    – gview
    Commented Jul 26, 2012 at 1:44
  • 2
    Indeed, but this is a simple enough way to get started.
    – Lusitanian
    Commented Jul 26, 2012 at 1:45
  • excellent answer!!, now the only question is where is the best place to dispatch a custom event?, maybe a service?
    – Nico
    Commented Aug 7, 2013 at 19:05
  • 1
    Events are usually dispatched in controllers, but can be also in dispatched in services if you need.
    – tomazahlin
    Commented May 8, 2014 at 0:07
  • Using the event_dispatcher service worked for me! I used $dispatcher = new EventDispatcher; but that did not fire my event for some reason.
    – Mirage
    Commented Jun 25, 2014 at 8:42
28

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);
2
  • Great! very helpful!
    – iamjc015
    Commented Sep 14, 2016 at 9:42
  • in my case giving error Service event_dispatcher not found why this error occur can you please help me asap thanks in advance
    – Pardeep K
    Commented May 3, 2019 at 11:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.