>上下文
我有一个配置文件,在其中我精确地MongoDB connection string
.我想测试我的MongoDB连接,以使用我的代码向开发人员精确说明,如果是这种情况,他们的配置是错误的。
我使用MongoDB驱动程序。
我没有找到任何关于 Mongo 连接测试的信息。
问题
我愿意:
<?php
$configuration = parse_ini_file("../configs/database.ini");
$mongo = new MongoDBClient($configuration['resources.mongo.dsn']);
$db = $mongo->stats;
但是抛出的唯一错误是关于MongoDB connection string
格式错误的错误。例如:
test_bad_string
,抛出MongoDBDriverExceptionInvalidArgumentException
使用
mongodb://127.0.0.1:270
(我的MongoDB的默认端口是27017
(,我没有看到任何错误
问题
有没有办法在PHP中测试与MongoDB数据库的连接?
好的,我找到了测试它的方法!
<?php
$mongo = new MongoDBClient('mongodb://my_server_does_not_exist_here:27017');
$dbs = $mongo->listDatabases();
如果连接失败,listDatabases
抛出MongoDBDriverExceptionConnectionTimeoutException
。您只需要在listDatabases
周围设置尝试/捕获即可。
对于类似 Mysql 的处理,您可以尝试以下操作:
$client = new MongoDBClient('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();
}
我正在查看上面的答案,并希望在使用它时与人们分享简单的单例实现。只需在任何设置了变量的类中使用它,它就会将类变成单例 mongo db 连接。
use MongoDBClient; // Used extension
trait MongoDbClient
{
private static ?MongoDBClient $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 MongoDBDriverExceptionConnectionTimeoutException("There is no connection yet");
}
} catch (MongoDBDriverExceptionConnectionTimeoutException $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 (MongoDBDriverExceptionConnectionTimeoutException $connectionTimeoutException){
throw $connectionTimeoutException;
}
}
}