I'm not sure this question belongs here since it's "debatable", but let's give it a try.
After reading lots of examples and questions about it (like this one which seems really similar), I still can't figure out if I should opt for polymorphism to replace a switch.
It's all about a Ratchet WebSocket server which receives JSON messages and executes a routine depending on the message type
:
public function onMessage(ConnectionInterface $from, $msg) {
/*!
Triggers everytime a message is received by the application.
Depending on @p $msg type, the application will broadcast @p $msg accordingly.
@param ConnectionInterface $from
This is the socket (client) who sent @p $msg.
@param string $msg
A JSON string sent by the client.
*/
$usermsg = json_decode($msg, true);
if (isset($usermsg["message"])) {
$actual_msg = $this->removeHTML($usermsg["message"]);
}
switch ($usermsg["type"]) {
case 'text':
$this->text($from, $actual_msg, "text");
break;
case 'token':
$this->token($from, $usermsg["im"]);
break;
case "ready":
$this->ready($from);
break;
case "action":
$this->text($from, $actual_msg, "action");
break;
case "users":
$this->whoIsOnline($from);
break;
case "listen":
$this->listen($from);
break;
case "end":
$this->finish($from, $actual_msg);
break;
case 'statInit':
$this->statInit($from);
break;
}
}
Thing is, $msg
is a string since it's JSON, no object is instantiated for any message that arrives at all. This is why there's no class hierarchy, because messages are not objects. In fact, there is no other class than the actual Server.
In any case, this is the only switch that exists server-side (there's another one in client, but it´s jQuery so it's a different story), so adding new functionality should be adding a case AND a method, not that hard. The project is not gonna grow much, but I'd like it to be easily scaled.
Should I stick with OOP design and create an object for each message that arrives and apply polymorphism? Seems a little bit overwhelming since the server handle chat messages.