php mongo类

2021-07-02 12:07

阅读:654

标签:func   方便   无法   sel   public   code   word   get   自己   

看了好多mongo类都不尽人意。最后发现根本不需要自己封装类。php mongo 的扩展自带的方法就已经很方便了

但是习惯性的把数据库连接部分封装起来。最后我就封装了一个单例模式的数据库类

使用单例模式是为了避免生成多个实例,浪费资源

下面是封装的代码

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 是选择的表。 因为使用单例模式,所以,只会实例一个资源
具体操作再参考下面的文章吧

这里有个一篇文章,讲的php对mongo的操作,很详细,也很易懂。希望大家参考下

http://www.cnblogs.com/jackluo/archive/2013/06/16/3138835.html

php mongo类

标签:func   方便   无法   sel   public   code   word   get   自己   

原文地址:http://www.cnblogs.com/zhaoyang-1989/p/7127972.html


评论


亲,登录后才可以留言!