本文主要介绍了php实现的mongodb单例模式操作类,结合实例形式分析了php基于单例模式操作mongodb数据库的数据库封装类相关实现技巧,需要的朋友可以参考下,希望能帮助到大家。
下面是封装的代码
class mongo_db
{
private static $cli;
/**
* 不允许初始化
*/
private function __construct()
{
$config = config::get('config.mongo_config');
if(empty($config)){
$this->throwerror('无法连接数据库!');
}
if (!empty($config["user_name"])) {
$this->mongo = new mongoclient("mongodb://{$config['user_name']}:{$config['password']}@{$config['host']}:{$config['port']}");
}else {
$this->mongo = new mongoclient($config['host'] . ':' . $config['port']);
}
}
/**
* 单例模式
* @return mongo|null
*/
public static function cli(){
if(!(self::$cli instanceof self)){
self::$cli = new self();
}
return self::$cli->mongo;
}
}
$mongo = mongo_db::cli()->test->mycollection; // test 是选择的数据库 , mycollection 是选择的表。 因为使用单例模式,所以,只会实例一个资源具体操作再参考下面的文章吧
相关推荐:
详解php7如何实现mongodb模糊查询
php实现单例模式的方法
php设计模式中工厂模式和单例模式的区别
以上就是php实现的mongodb单例模式实例操作分享的详细内容。