Blame view

yaf/Hood/Dao/MongoDB/MongoCore.php 9.01 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
<?php
/**
 * Created by PhpStorm.
 * User: Zip
 * Date: 15/6/10
 * Time: 上午10:55
 */

namespace Hood\Dao\MongoDB;

use Hood\Core\Root;

class MongoCore extends Root
{
    private static $_lastId;

    /**
     * @var \MongoClient
     */
    private $_mongo = null;

    private $_dbname = '';

    private $targetOptions = array(
        'connectTimeoutMS' => 3,
        'connect' => true
    );

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @param array $options
     * @return $this
     */
    public function setTargetOptions(array $options = array())
    {
        $this->targetOptions = array_merge($this->targetOptions, $options);
        return $this;
    }

    private function _connect($dbname, $modality = 'proxy')
    {
        $this->_dbname = $dbname;
        $server = $this->getServerHost('nosql');
        $_serverConfig = $server->getServerConfig('database', $this->_dbname);
        if (empty($_serverConfig)) {
            throw new MongoException('Mongo Servers Config Not DBName "' . $this->_dbname . '" <br />Config File: ' . $this->serviceFile);
        }
        $options = $server->getServerConfig('mongo');
        $this->targetOptions = array_merge($this->targetOptions, $options);
        $targetOptions = array();
        if (!empty($this->targetOptions['target_sock']) && !empty($_serverConfig['username']) && !empty($_serverConfig['passwd'])) {
            $targetOptions["username"] = $_serverConfig['username'];
            $targetOptions["password"] = $_serverConfig['passwd'];
        }
        unset($this->targetOptions['target_sock']);
        switch ($modality) {
            case 'write':
                $hosts = $_serverConfig['write'];
                break;
            case 'read':
                $hosts = $_serverConfig['read'];
                break;
            case 'proxy':
                $hosts = $_serverConfig['proxy'];
                break;
            default:
                throw new MongoException('Not Mongo Hosts.');
        }
        $server = null;
        if (isset($_serverConfig['sock']) && !empty($_serverConfig['sock'])) {
            $server = "mongodb://" . $_serverConfig['sock'];
        } else {
            $server = "mongodb://" . $hosts;
        }
        if (class_exists("MongoClient")) {
            $this->_mongo = new \MongoClient($server, $this->targetOptions);
        } else {
            $this->_mongo = new \Mongo($server, $this->targetOptions);
        }
    }

    /**
     * 关闭
     * @param $connection
     * @return bool
     */
    public function close($connection)
    {
        return $this->_mongo->close($connection);
    }

    /**
     * 创建连接
     * @return bool
     */
    public function connect()
    {
        return $this->_mongo->connect();
    }

    /**
     * 清理DB
     * @param $db
     * @return mixed
     */
    public function dropDB($db)
    {
        if (!is_object($db)) {
            $db = $this->selectDB($db);
        }
        if (method_exists($db, "drop")) {
            return $db->drop();
        }
        if (method_exists($this->_mongo, "dropDB")) {
            $this->_mongo->dropDB($db);
        }
    }

    /**
     *
     * @return bool
     */
    public function forceError()
    {
        if (method_exists($this->_mongo, "forceError")) {
            return $this->_mongo->forceError();
        }
        return false;
    }

    /**
     * @param $dbname The database name
     * @return \MongoDB
     */
    public function __get($dbname)
    {
        return $this->_mongo->$dbname;
    }

    /**
     * 获取Hosts
     * @return array
     */
    public function getHosts()
    {
        if (method_exists($this->_mongo, "getHosts")) {
            return $this->_mongo->getHosts();
        }
        return array();
    }

    /**
     * Get the read preference for this connection
     * @return array
     */
    public function getReadPreference()
    {
        if (method_exists($this->_mongo, "getReadPreference")) {
            return $this->_mongo->getReadPreference();
        }
        return array();
    }

    /**
     * 最后一个错误
     * @return array|null
     */
    public function lastError()
    {
        if (method_exists($this->_mongo, "lastError")) {
            return $this->_mongo->lastError();
        }
        return array();
    }

    /**
     * Lists all of the databases available
     * @return array
     */
    public function listDBs()
    {
        return $this->_mongo->listDBs();
    }

    /**
     * Connect pair servers
     *
     * @return boolean
     */
    public function pairConnect()
    {
        if (method_exists($this->_mongo, "pairConnect")) {
            return $this->_mongo->pairConnect();
        }
        return false;
    }

    /**
     * Create pair persist connection
     *
     * @param string $username
     * @param string $password
     * @return boolean
     */
    public function pairPersistConnect($username = "", $password = "")
    {
        if (method_exists($this->_mongo, "pairPersistConnect")) {
            return $this->_mongo->pairPersistConnect($username, $password);
        }
        return false;
    }

    /**
     * Create persist connection
     *
     * @param string $username Username
     * @param string $password Password
     * @return boolean
     */
    public function persistConnect($username = "", $password = "")
    {
        if (method_exists($this->_mongo, "persistConnect")) {
            return $this->_mongo->persistConnect($username, $password);
        }
        return false;
    }

    /**
     * Get previous error
     *
     * @return array
     */
    public function prevError()
    {
        if (method_exists($this->_mongo, "prevError")) {
            return $this->_mongo->prevError();
        }
        return array();
    }

    /**
     * Reset error
     *
     * @return array
     */
    public function resetError()
    {
        if (method_exists($this->_mongo, "resetError")) {
            return $this->_mongo->resetError();
        }
        return array();
    }

    /**
     *
     * @param $db
     * @param $collection
     * @return \MongoCollection
     */
    public function selectCollection($dbname, $collection)
    {
        if ($this->_mongo == null) {
            $this->_connect($dbname);
        }
        return $this->_mongo->selectCollection($dbname, $collection);
    }

    /**
     * @return Collection
     */
    public function collection($dbname, $collection)
    {
        if ($this->_mongo == null) {
            $this->_connect($dbname);
        }
        $collection = new Collection($this->_mongo, $dbname, $collection);
        return $collection;
    }

    /**
     * Gets a database
     *
     * @param string $db The database name
     * @return \MongoDB
     */
    public function selectDB($dbname)
    {
        if ($this->_mongo == null) {
            $this->_connect($dbname);
        }
        return $this->_mongo->selectDB($dbname);
    }

    /**
     * 为该连接设置读取选项
     * @param $readPreference mode: Mongo::RP_PRIMARY, Mongo::RP_PRIMARY_PREFERRED, Mongo::RP_SECONDARY, Mongo::RP_SECONDARY_PREFERRED, or Mongo::RP_NEAREST
     * @param array $tags
     * @return bool
     */
    public function setReadPreference($readPreference, array $tags = array())
    {
        if (method_exists($this->_mongo, "setReadPreference")) {
            return $this->_mongo->setReadPreference($readPreference, $tags);
        }
        return false;
    }

    /**
     * Change slaveOkay setting for this connection
     *
     * @param boolean $ok If reads should be sent to secondary members of a replica set for all possible queries using this Mongo instance
     * @return boolean
     */
    public function setSlaveOkay($ok)
    {
        if (method_exists($this->_mongo, "setSlaveOkay")) {
            return $this->_mongo->setSlaveOkay($ok);
        }
        return false;
    }

    /**
     *
     * 输出Mongo对象
     * @return string
     */
    public function __toString()
    {
        return $this->_mongo->__toString();
    }

    /**
     *
     * 获取版本号
     * @return string
     */
    public static function getVersion()
    {
        if (class_exists("MongoClient")) {
            return \MongoClient::VERSION;
        }
        if (class_exists("Mongo")) {
            return \Mongo::VERSION;
        }
        return "0";
    }

    /**
     * Compare another version with current version
     *
     * @param string $version Version to compare
     * @return integer -1,0,1
     * @since 1.1.4
     */
    public static function compareVersion($version)
    {
        $currentVersion = self::getVersion();
        preg_match("/^[\\.\\d]+/", $currentVersion, $match);
        $number = $match[0];
        return version_compare($number, $version);
    }

    /**
     * 设置最后插入的ID
     * @param $lastId
     */
    static function setLastInsertId($lastId)
    {
        self::$_lastId = $lastId;
    }

    /**
     *
     * 获取插入刚刚插入的ID
     * @return string
     */
    static function lastInsertId()
    {
        return self::$_lastId;
    }
}