Help with PHP and Mongodb

Asked

Viewed 48 times

0

Hello.

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

I have the following code that connects to 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 function findNome() opens a new connection with Mongo. Is there any way to leave that connection open? needing to call it only once?

Note: This function is called via ajax using jQuery

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;
}

Mongodb lib persistence for PHP

I searched the https://docs.mongodb.com/php-library/, but I found nothing about persistence, it is likely that only a server with support to create Sockets and with this use Websocket you will be able to maintain the connection. But it’s something very complex and I’d have to redo a lot, from your back-end to your front-end, if I find anything I’ll edit the answer.

  • Does this method work via ajax? I edited my question by placing the observation

  • @Ajax user is in front-end, this is not related to Ajax, php runs in back-end ;)

  • Would it be possible to leave the connection open in php? so when calling via ajax you don’t have to connect again to Mongo? I thought about using websocket but I don’t know how.

  • @Ajax user no, I searched https://docs.mongodb.com/php-library/, but I did not find anything about persistence, it is likely that only a server with support to create Sockets and with this use Websocket you will be able to maintain the connection. But it’s something very complex and I would have to redo a lot, from your back-end to your front-end.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.