最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
php实现的mongoDB单例模式操作类的教程
时间:2022-06-24 18:41:39 编辑:袖梨 来源:一聚教程网
小编给大家分享的这篇文章介绍了php实现的mongoDB单例模式操作类的教程,有需要的朋友请参考本文。
看了好多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 是选择的表。
相关文章
- 《弹壳特攻队》永久不过期的最新可用兑换码合集 06-16
- 《暖雪》终业DLC新流派灵剑修罗开荒有哪些 06-16
- Metaplanet 砸 1.17 亿美元加码比特币!持币量突破 1 万枚、超越 Coinbase 06-16
- 《魔力宝贝:复兴》1~30级主线困难有哪些快速通关方法 06-16
- 《欢乐钓鱼大师》稀有鱼垂钓有哪些方法 06-16
- SNORT币手续费低吗?2025币安交易所低成本教程 06-16