1

I'm studying Symfony but I don't Understand The Dispatch custom Event

when I have to dispatch event ? inside the Controller?

I have to repeat this code

// the order is somehow created or retrieved
$order = new Order();
// ...

// create the FilterOrderEvent and dispatch it
$event = new FilterOrderEvent($order);
$dispatcher->dispatch(StoreEvents::STORE_ORDER, $event);

AnyTime I want an Event?

In this Example what is the advantage to dispatch this event?

1 Answer 1

2

You can dispatch an event whenever you want - in controller, in dataProvider or in any other place in which you have access to EventDispatcher.

As stated in symfony doc:

The Symfony EventDispatcher component implements the Mediator pattern in a simple and effective way to make all these things possible and to make your projects truly extensible.

Advantage of using events is that your controller class (or any other you dispatch event from) is totally decoupled from real event handling. You can think of it like "fire and forget" meaning that you just dispatch an event - who and what will be done with that is not your business.

In your example you just add an order and dispatch event. When someone will be writing plugin for your system he/she will just add listener for that event and will handle it in his/her way - for example send email that order was added or reindex search engine. Note that you can add multiple event listeners to the same event.

Read more about Mediator pattern

Sign up to request clarification or add additional context in comments.

5 Comments

thanks for reply. I know mediator Pattern. Then My custom Event is the mediator ? In my Event can I have a service or code to send Email ?
No, EventListener is a mediator - not Event. Code to send email should be in EventListener. symfony.com/doc/current/cookbook/event_dispatcher/…
Right, and in my Event I have the Method of Event Listener?
no, EventListener should have a method which accepts your Event as a parameter - it's all in the doc
Thanks now I Understand

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.