一起源码网

标题: php实现的mongoDB单例模式实例操作分享 [打印本页]

作者: 云文章    时间: 2020-6-7 11:30
标题: php实现的mongoDB单例模式实例操作分享
本文主要介绍了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 是选择的表。 因为使用单例模式,所以,只会实例一个资源具体操作再参考下面的文章吧



作者: 兵棕    时间: 2022-10-18 09:49
音源下载网




欢迎光临 一起源码网 (https://www.171739.xyz/) Powered by Discuz! X3.3