本文实例讲述了php实现的mongoDB单例模式操作类。分享给大家供大家参考,具体如下:
看了好多mongo类都不尽人意。最后发现根本不需要自己封装类。php mongo 的扩展自带的方法就已经很方便了
但是习惯性的把数据库连接部分封装起来。最后我就封装了一个单例模式的数据库类
使用单例模式是为了避免生成多个实例,浪费资源
下面是封装的代码
01
class Mongo_db
02
{
03
private static $cli;
04
/**
05
不允许初始化
06
*/
07
private function __construct()
08
{
09
$config = Config::get('config.mongo_config');
10
if(empty($config)){
11
$this->throwError('无法连接数据库!');
12
}
13
if (!empty($config["user_name"])) {
14
$this->mongo = new MongoClient("mongodb://{$config['user_name']}:{$config['password']}@{$config['host']}:{$config['port']}");
15
}else {
16
$this->mongo = new MongoClient($config['host'] . ':' . $config['port']);
17
}
18
}
19
/**
20
单例模式
21
@return Mongo|null
22
*/
23
public static function cli(){
24
if(!(self::$cli instanceof self)){
25
self::$cli = new self();
26
}
27
return self::$cli->mongo;
28
}
29
}
30
$mongo = Mongo_db::cli()->test->mycollection; // test 是选择的数据库 , mycollection 是选择的表。 因为使用单例模式,所以只会实例一个资源。
本文原创自news.mkq.online