How to trigger an event in an EventListener?

57 Views Asked by At

I'm writing a PHP application and want to implement the Mediator pattern for the core part of my business logic. This "core" is actually some kind of game with a lot of events and statuses. So the event driven handling of it seems to be the optimal approach.

The mediator pattern itself is no problem. I only have to create an EventDispatcher and attach some Listeners to it.

(Actually in my concrete case it's a bit more complex: The Listeners need to implement something like Chain-of-responsibility or State pattern, in order to handle the same event in different ways according to the current state of the process.)

The problem is, that handling of an event can change the state of the process and cause further events. That means, the listeners should be able to trigger events. That means:

  1. They need to know the EventDispatcher. So the EventDispatcher needs either to be injected via the constructor or to be passed into the notification (notify(string $eventName, Event $event, EventDispatcher $eventDispatcher)) method.
  2. Every listener needs to know everything about the specifics of all the events it triggers. Injecting them won't be a practicable solution. And so we'll get a lot of new MyEvent(...) statements in the listeners and the code will become harder to test.

Both has for me a putrid smell...

How to solve this dilemma and let the code clean, when EventListeners trigger events?

0

There are 0 best solutions below