This article explains how to implement the mongoDB singleton mode operation class in PHP.
I have seen many mongo classes and they are all unsatisfactory. Finally, I found that there was no need to encapsulate the class myself. The methods that come with the php mongo extension are already very convenient
, but it is customary to encapsulate the database connection part. Finally, I encapsulated a singleton mode database class
The singleton mode is used to avoid generating multiple instances and wasting resources
The following is the encapsulated code
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
This article explains how to implement the mongoDB singleton mode operation class in PHP. For more related content, please pay attention to the PHP Chinese website.
Related recommendations:
PHP WeChat development: WeChat recording temporary conversion to permanent storage
php is created using the imagecopymerge() function Translucent watermark method
Discuz! Tutorial: How to modify theme views through a simple php file?
The above is the detailed content of How to implement mongoDB singleton mode operation class in PHP. For more information, please follow other related articles on the PHP Chinese website!