时间:2021-07-01 10:21:17 帮助过:3人阅读
下面是封装的代码
- 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单例模式实例操作分享的详细内容,更多请关注Gxl网其它相关文章!