MongoCore.php 9.01 KB
<?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' => 5000,
        '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;
    }
}