<分区>
我不确定这个问题属于这里,因为它“值得商榷”,但让我们试一试。
在阅读了很多关于它的例子和问题之后(比如 this one 看起来真的很相似),我仍然不知道我是否应该选择多态来代替开关。
都是关于 Ratchet WebSocket 服务器的,它接收 JSON 消息并根据消息 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;
}
}
事实是,$msg
是一个字符串,因为它是 JSON,根本没有为到达的任何消息实例化任何对象。这就是没有类层次结构的原因,因为消息不是对象。事实上,除了实际的服务器之外没有其他类。
无论如何,这是唯一存在于服务器端的开关(客户端中还有另一个开关,但它是 jQuery,所以情况不同),因此添加新功能应该是添加一个案例和一个方法,而不是那么难。该项目不会增长太多,但我希望它能够轻松扩展。
我是否应该坚持 OOP 设计并为到达的每条消息创建一个对象并应用多态性?似乎有点不知所措,因为服务器处理聊天消息。