W
W
WebDev2022-04-14 21:43:25
PHP
WebDev, 2022-04-14 21:43:25

What is the correct way to create an EventSubscriber?

Let's say I have an Employee entity. And in the controller, when a new employee is created, I dispatch an event

$this->eventDispatcher(new EmployeeCreatedEvent());

Now, when creating an employee, I want to send a notification to the general channel in Slack that we have a new employee in our company. Meet him etc.
To do this, I will subscribe to this event in the slack component and send a message.
I have a question, how should the subscriber look like?
Option 1: The subscriber is named EmployeeCreatedSubscriber and contains a method to send a message. And this seems logical to me, because this is exactly the subscriber, which means he must subscribe to a specific event. Probably for one.
Option 2: The subscriber is called GreetingsMessageSubscriber. Internally, it is subscribed to EmployeeCreatedEvent and other events, if any. It sends messages with a greeting and is subscribed to all events, upon the occurrence of which it is necessary to send a message to the slack.
In short, in the first case, the subscriber processes exactly one event, in the second, a group of events.
Which option are you using and which one do you think is correct?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Svyatoslav Grafov, 2022-04-25
@moefag

By using expressions from the abbreviation CRUD in the names of business logic events, I will assume that the application is relatively simple, and events will not be reused. If you are not going to hang several handlers on this event, then I recommend not to complicate it and just make sure that the logic of the controller, sending messages and storing templates is separated from each other.
An example of using the subscription system in Symfony can be seen in the validation system. There is just the reuse of events in their own system, and the points to which you can connect with custom code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question