简体   繁体   中英

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

I'm using Symfony 4 and there are custom event and subscriber, eg CustomEvent and CustomEventSubscriber. There is module which dispatch CustomEvent, eg 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, eg container?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM