我使用的是laravel 5.2和MongoDB 3.2。
我想在我的应用程序启动之前测试连接是否正常(我不能使用DB facade),在独白配置中。如果连接不正常,我将使用登录文件。
根据建议,我正在测试MongoClient, Mongo和MongoDB'Client,并使用任何启用。
我正在尝试测试mongo连接如下:
$mongoClient = new 'MongoDB'Client('mongodb://localhost:27017');
$mongoClient->selectCollection('mydb', 'mycollection');
这是返回:
Client {
+manager: Manager {#21}
+uri: "mongodb://localhost:27017"
+typeMap: [
array => "MongoDB'Model'BSONArray",
document => "MongoDB'Model'BSONDocument",
root => "MongoDB'Model'BSONDocument"
]
}
最后,我的问题:
- 存在一种在应用程序启动之前使用DB facade的方法? 如何以及什么是正确的方式来测试MongoDB连接PHP?
如果您有其他建议,我将不胜感激。
根据PHP文档,the driver connects to the database lazily
(http://php.net/manual/en/mongodb-driver-manager.getservers.php),测试连接的唯一方法应该是实际执行您评论中所述的findOne()
命令。
此外,如果DB或Collection的名称不确定,您可以使用listDatabases()
方法,该方法也会在连接失败时抛出异常。
使用这种方式可以检查MongoDB与PHP的连接:
$connection = new MongoClient(); // connects to localhost:27017
$connection = new MongoClient( "mongodb://example.com" ); // connect to a remote host (default port: 27017)
$connection = new MongoClient( "mongodb://example.com:65432" ); // connect to a remote host at a given port