在websockets PHP中使用数据库连接是否很好?

时间:2019-06-03 21:30:17

标签: php pdo ratchet

我是新程序员,正在从事一个symfony项目,该项目是 一个简单的社交网络。因此,我想知道这样直接在棘轮中使用数据库连接是一种不好的做法:

class Chat implements MessageComponentInterface
{
private $pdo;
protected $clients;

public function __construct() {
    $this->pdo = new \PDO('mysql:host=localhost;dbname=symfony_social_network;charset=utf8', 'root', null);;
    $this->clients = [];
}

然后在这样的函数中使用它:

public function onMessage(ConnectionInterface $from, $msg) {
    $msgContent = json_decode($msg, true);
    switch ( $msgContent['command'] ) {
        case 'addMessage':
            $this->addMessage($myId, $msgContent, $from);
            break;
        .....
}

添加消息功能:

private function addMessage($myId, $msg)
{
    $acceptUser = htmlspecialchars($msg['acceptUser']);
    $dateNow    = htmlspecialchars(date('Y-m-d H:i:s'));
    $content    = htmlspecialchars($msg['content']);
    $sql = 'INSERT INTO messages (`accept_user`, `send_user`, `content`, `date_added`, `is_delivered`, `is_seen`)
            VALUES (?, ?, ?, ?, ?, ?)';

    $stmt = $this->pdo->prepare($sql);

    if ( isset($this->clients[$acceptUser]) ) {
        $stmt->execute([$acceptUser, $myId, $content, $dateNow, 1, 0]);
    }else {
        $stmt->execute([$acceptUser, $myId, $content, $dateNow, 0, 0]);
    }
    return $this->pdo->lastInsertId();
}

或者最好使用AJAX。然后使用ZMQ将消息发送到websocket,然后使用websocket发送给特定用户。像这样:

/**
 * @Route("/addMessage", methods={"POST"})
 */
public function addMessage(Request $request) {

        ....

        $context   = new \ZMQContext(1);
        $socket    = $context->getSocket(\ZMQ::SOCKET_PUSH);
        $socket->connect("tcp://127.0.0.1:5555");
        $socket->send(json_encode($arr));
}

0 个答案:

没有答案