PHP封装一个MongoDB单例类

188 阅读1分钟

代码如下:

<?php

namespace app\index\cache;

/**
 * MongoDB单例类
 *
 */
class Mongo {
    private static $ins     = [];
    private static $def     = "test";
    private $_conn          = null;
    private $_db            = null;
    private static $_config = [
        "test" => ["url" => "mongodb://127.0.0.1:27017","dbname" => "mydb1"], //默认连接该库
    ];

    /**
     * 创建实例
     * @param  string $confkey
     * @return \Mongo
     */
    public static function getInstance($confkey = NULL) {
        if (!$confkey) {
            $confkey = self::$def;
        }
        if (!isset(self::$ins[$confkey]) && ($conf = self::$_config[$confkey])) {
            $m = new Mongo($conf);
            self::$ins[$confkey] = $m;
        }
        return self::$ins[$confkey];
    }

    /**
     * 构造方法
     */
    private fun