Notice: Undefined variable: eventDispatcher?

609 Views Asked by At

Hey brothers I'm stack in this problem I'm trying to make and event to send email to any new user done his registration but I don't know what's wrong

enter image description hereenter image description here

2

There are 2 best solutions below

2
xabbuh On BEST ANSWER

You generally do not want to create a new event dispatcher instance in your controller. When doing so your controller would also be responsible for attaching all the listeners which quite contradicts the loose coupling between the code dispatching an event and the parts of your application listening to these events.

Instead you will probably want to use the event_dispatcher service. In modern Symfony applications all you need to do is to add an extra argument to your controller action that is type-hinted with the EventDispatcherInterface (just like you are already doing it with the password encoder):

use Symfony\Component\EventDispatcher\EventDispatcherInterface;

public function registerAction(Request $request, UserPasswordEncoderInterface $passwordEncoder, EventDispatcherInterface $eventDispatcher)
{
    // ...
}
3
iiirxs On

You should create an EventDispatcher object before using it:

use Symfony\Component\EventDispatcher\EventDispatcherInterface;
....
public function registerAction(..., EventDispatcherInterface $eventDispatcher)
{

    $event = new GenericEvent($user);
    $eventDispatcher->dispatch(Events::USER_REGISTERED, $event);
}

EDIT: xabbuh is right. My code block assumed you have added your registration listeners to the dispatcher. Indeed, this prevents the decoupling that EventDispatcher component tries to provide. Furthermore, one shouldn't create objects in controller using new whenever possible, using dependency injection and/or factory pattern instead.

In your case, you should inject the EventDispatcher service (through EventDispatcherInterface) in your controller, using autowiring by type-hinting like above.