繁体   English   中英

有没有办法在 PHP 中测试 MongoDB 连接?

[英]Is there a way to test MongoDB connection in PHP?

语境

我有一个配置文件,我在其中精确了MongoDB connection string 我想测试我的 MongoDB 连接,准确地告诉使用我的代码的开发人员他们的配置是错误的,如果是这样的话。

我使用MongoDB 驱动程序

我没有找到任何关于 Mongo 连接测试的信息。

问题

我愿意:

<?php
$configuration = parse_ini_file("../configs/database.ini");
$mongo = new MongoDB\Client($configuration['resources.mongo.dsn']);
$db = $mongo->stats;

但抛出的唯一错误是关于MongoDB connection string格式错误的错误。 例如:

  • 使用test_bad_string ,抛出MongoDB\\Driver\\Exception\\InvalidArgumentException

  • 使用mongodb://127.0.0.1:270 (我的 MongoDB 的默认端口是27017 ),我没有看到任何错误

有没有办法在 PHP 中测试与 MongoDB 数据库的连接?

好的,我找到了一种方法来测试它!

<?php
$mongo = new MongoDB\Client('mongodb://my_server_does_not_exist_here:27017');
$dbs = $mongo->listDatabases();

如果连接失败, listDatabases会抛出MongoDB\\Driver\\Exception\\ConnectionTimeoutException 您只需要在listDatabases周围设置一个 try/catch 。

嗨,我正在查看上面的答案,并希望在我使用它时与人们分享简单的单例实现。 只需在设置了变量的任何类中使用它,它就会将类转换为单例 mongo db 连接。

使用 MongoDB\\Client; // 使用的扩展名

特征 MongoDbClient {

private static ?\MongoDB\Client $client = null;

/**
 * @return Client
 * the single function able to get the connection from, will check if the connection is alive and will route to the new instance factory method
 */
public static function getInstance(){
    try {

        if(self::$client instanceof Client){
            self::$client->listDatabases();
            return self::$client;
        } else {
            throw new \MongoDB\Driver\Exception\ConnectionTimeoutException("There is no connection yet");
        }

    } catch (\MongoDB\Driver\Exception\ConnectionTimeoutException $connectionTimeoutException){
        return self::newInstance();
    }
}

/**
 * @return string
 * creates a connection string based on the static properties available which this trait is used
 */
private static function getMongoDbConnectionUri():string
{
    return 'mongodb://' . self::$user . ':' . self::$pass . '@' . self::$host . ':' . self::$port . '/?authMechanism=' . self::$authMechanism . '&authSource=' . self::$authSource;
}


/**
 * @return Client
 * sets and returns a new client but throws a exception if a new connection timeout occurs
 */
private static function newInstance(): Client
{
    try {
        self::$client = new Client(self::getMongoDbConnectionUri());
        return self::$client;
    } catch (\MongoDB\Driver\Exception\ConnectionTimeoutException $connectionTimeoutException){
        throw $connectionTimeoutException;
    }
}

}

对于 Mysql 之类的处理,您可以尝试以下操作:

 $client = new MongoDB\\Client('mongodb://my_server_does_not_exist_here:27017'); try{ $dbs = $client->listDatabases(); echo '<pre>'; print_r($dbs); echo '</pre>'; // Or Nothing if you just wanna check for errors } catch(Exception $e){ echo "Unable to connect to Database at the moment ! "; exit(); }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM