Andrey Lebedev
Andrey Lebedev

Reputation: 151

How in a Symfony 4 pass context to the custom event subscriber?

I'm using Symfony 4 and there are custom event and subscriber, e.g. CustomEvent and CustomEventSubscriber. There is module which dispatch CustomEvent, e.g. CustomModule. And that module is using in the controller (ControllerA) and command (CommandB).

In other words possible two follow scenarios:

ControllerA -> CustomModule -> CustomEventSubscriber(CustomEvent)

Or

CommandB -> CustomModule -> CustomEventSubscriber(CustomEvent)

Logic in the CustomEventSubscriber little bit different depends on where was called CustomModule (ControllerA or CommandB).

How to pass that information to the CustomEventSubscriber?

I can add $context property to the CustomEvent and set it in the CustomModule. But in that case I should pass info about context to the CustomModule.

Or maybe I can use some global settings, e.g. container?

Or create two different event subscribers per CustomEvent, disable auto-wiring, and 'manually' init and add to the dispatcher in ControllerA and CommandB?

Upvotes: 0

Views: 903

Answers (1)

yivi
yivi

Reputation: 47559

No need to create globals, to pass around the container, or any other anti-pattern mechanism.

The obvious place to pass information from where the event is dispatched to where the event is handled, is the event itself.

Ideally, you would create your own custom event class, with whatever properties you need to perform the work down the line.

The custom event would be tailored to your application, and you could listen to those events specifically without having to check with getSubject() to see the listener should really handle that one.

Using a Generic is fine, although much less expressive. If you dispatch(new CustomerCreatedEvent()) it's immediately obvious what's going on.

That's the event your subscriber should listen to, and it would already contain all the necessary information gathered on the dispatching context.

Upvotes: 1

Related Questions