3

I guess I'm missing something in the documentation, but the question is pretty simple.

Let's say I have a message of class MessageOne and MessageTwo which extends MessageOne.

I also have MessageOneHandler which should handle MessageOne:

__invoke(MessageOne $messageOne)

And MessageTwoHandler which should handle only MessageTwo:

__invoke(MessageTwo $messageTwo)

And the problem is when MessageTwo is dispatched it is being handled by both MessageHandlerOne and MessageHandlerTwo. Yes, it is completely sensible due to inheritance and everything is logically correct, but are there any "symfony" ways to prevent that?

Of course, I can solve this issue by reworking of the inheritance of these classes, but is there maybe a better way?

Moreover debug:messenger shows everything as expected, one handler per one message class without inheritance issues.

yivi
  • 42,438
  • 18
  • 116
  • 138
Gino Pane
  • 4,740
  • 5
  • 31
  • 46

1 Answers1

4

Inheritance rarely will be a god fit for messages.

If MessageTwo extends MessageOne, then $messageTwo instanceof MessageOne would return true, simple as that.

Also, messages should be very simple and lightweight, so code repetition shouldn't be generally a concern. But if for some reason you do need to reuse some code between message classes, you have a few options:

  • You could short-circuit the handling so that if get_class($message) !== MessageOne::class then then handler could return without doing any work... but personally I feel it would be a brittle design.

The better options are simply reworking the inheritance model for your messages.

  • Shared logic between MessageOne and MessageTwo could be moved to a parent AbstractMessage, from which both inherit. Handlers would correctly type-hint the concrete message type, and there would be no confusion.

  • Depending on the type of code reuse you are going for, you could move the shared code to a Trait or a helper class with static methods. If either of these are any good would depend entirely on the specifics of your application, and in the end would be a matter of opinion.

yivi
  • 42,438
  • 18
  • 116
  • 138
  • Yep, I'm already on option 1. So it looks like I'm not missing anything and everything is just as expected? – Gino Pane Jun 01 '20 at 08:47