Help with PHP and MongoDB

0

Hello.

I have an application using PHP and MongoDB and wanted to know if there is any way to keep the connection to mongoDB open.

I have the following code that connects to the mongo:

private static function findNome($nome) : String {
    $cliente = new \MongoDB\Client("mongodb://192.168.15.100:27017");
    $db = $cliente->dbName;
}

Every time I call the findNome() function, it opens a new connection with the mongo. Can you leave this connection open? need calling only once?

Note: This function is called via ajax using jQuery

    
asked by anonymous 23.04.2018 / 19:08

1 answer

4

You can create a variable in the class and do so and create a method to check if it is already connected:

private static $mongo;

private static checkConnection()
{
     if (!self::$mongo) {//Verifica se já esta conectado
         self::$mongo = new \MongoDB\Client("mongodb://192.168.15.100:27017");
     }
}

private static function findNome($nome) : String {
    $db = self::$mongo->dbName;
}

Persistence with the MongoDB lib for PHP

I searched the link , but found nothing about persistence, it is likely that only a server with support for creating Sockets and with this use WebSocket you will be able to maintain the connection. But it's quite complex and I'd have to do a lot of redoing, from your backend to your front end, if I find something I'll edit the answer.

    
23.04.2018 / 19:16