mongo php類

<?php
/**
 * mongo 類
 * User: wujp <[email protected]>
 * Date: 13-10-12
 * Time: 下午5:48
 */

class Mongo_DB
{
    #鏈接
    public $conn = null;

    #mongodb
    public $db = null;

    #鏈接參數
    private $url = '';

    #判斷db是否鏈接
    private $collected = null;

    #查詢、更新 映射 有|
    private $four_map = array( #值是字符串,值不用處理
        '>' => '$gt',
        '>=' => '$gte',
        '<' => '$le',
        '<=' => '$lte',
        '!=' => '$ne',
        '@' => '$exists', #鍵是否存在
        '?' => 'perl', #正則
    );
    private $ele_map = array( #數組,值需要處理
        '~' => '$elemMatch' #內嵌文檔
    );
    private $log_map = array( #值必須是數組
        '^' => '$in',
        '!^' => '$nin',
        '*' => '$all', #指定數組元素
    );
    #沒有|
    private $lgi_map = array( #必須是二維數組
        '$' => '$or',
        '&' => '$and',
    );
    private $where_map = array(
        '%' => '$where', #javascript 函數
    );
    private $sort_map = array(
        'DESC' => -1,
        'ASC' => 1
    );
    #當前db下所有集合=>鍵數組
    public $collections = null;

    #基本配置參數
    private $config = array(
        'host' => 'localhost',
        'port' => '27017',
        'dbname' => '',
        'user' => '',
        'pass' => '',
        'logpath' => '', #日誌目錄
        'replicaset' => array( #集羣
            'host' => array()
//            'host' => array('host:port'), #主機羣
//            'options' => array('readPreference', 'readPreferenceTags', 'replicaSet','slaveok')
        ),
    );


    /**
     * 構造函數,基本參數設置
     * @param $config
     *
     */
    public function __construct($config)
    {
        if (is_array($config) && $config) {
            foreach ($this->config as $k => $v) {
                if (isset($config[$k]) && $config[$k])
                    $this->config[$k] = !is_array($config[$k]) ? trim($config[$k]) : $config[$k];
            }

            $this->connect();
        }
    }

    /**
     * 初始化mongo
     *
     */
    private function connect()
    {
        if (!extension_loaded('mongo'))
            exit('ERROR:MONGO EXTENSION NOT LOAD');

        if ($this->conn === NULL) {
            try {
                if ($this->config['replicaset']['host']) {
                    #todo 主從配置,或者副本集,讀擴展,
                } else {
                    $this->url .= "mongodb://{$this->config['user']}:{$this->config['pass']}@{$this->config['host']}:
                    {$this->config['port']}/{$this->config['dbname']}";

                    $this->conn = new MongoClient($this->url);
                }

                $this->db = $this->conn->selectDB($this->config['dbname']);
                if ($this->db) {
                    $this->collected = true;
                    $this->GetAllCollection(); #獲取所有集合列表
                }
            } catch (MongoConnectionException $e) {
                $this->ErrLog($e->getMessage());
                exit('MONGO CONNECT ERROR');
            }
        }
    }

    /**
     * 析構函數
     */
    public function __destruct()
    {
        $this->collected = $this->collections = $this->db = $this->conn = null;
    }

    /**
     * 獲取db下所有集合名稱
     *
     * @internal param $dbname
     * @return bool
     */
    private function GetAllCollection()
    {
        if (!$this->collected)
            return false;

        $colls = $this->db->listCollections();
        if ($colls) {
            foreach ($colls as $v) {
                $pos = strpos($v, $this->config['dbname']);
                if ($pos !== false)
                    $this->collections[] = substr($v, ($pos + strlen($this->config['dbname']) + 1));
            }

            return true;
        } else {
            return false;
        }
    }

    /**
     * 初始化集合對象
     * @param $collname 集合名
     * @return mixed
     */
    public function GetMonCollection($collname)
    {
        if (!$this->collected)
            return false;

        return $this->db->selectCollection($collname);
    }

    /**
     * 轉換字符編碼
     * @param $array
     * @return bool
     */
    private function ConvertEncode($array)
    {
        if (is_array($array)) {
            foreach ($array as &$v) {
                if (is_array($v)) {
                    $v = $this->ConvertEncode($v);
                    if (!$v)
                        return false;
                } else {
                    $code = mb_detect_encoding($v, array('UTF-8', 'ASCII', 'GB2312', 'GBK', 'CP936'), true);
                    if ($code !== 'UTF-8')
                        $v = mb_convert_encoding($v, 'UTF-8', $code);
                }
            }

            return $array;
        }
        return false;
    }

    /**
     * 獲取where參數
     * @param $where
     * @param bool $type
     * @return string
     *
     */
    private function GetWhere($where, $type = false)
    {
        $wheres = array();
        $maps = array('four_map', 'log_map', 'ele_map');
        $maps_np = array_merge($this->lgi_map, $this->where_map);

        if (is_array($where) && $where) { #過濾查詢條件
            foreach ($where as $field => $val) {
                $pos = strpos($field, '|');

                if ($pos !== false) { #四則、正則、函數、數組、in、多重條件內嵌文檔
                    $tep = substr($field, 0, $pos);
                    $key = substr($field, ($pos + 1));

                    if ($key !== false) {
                        foreach ($maps as $v) {
                            $arr = $this->$v;
                            if (in_array($tep, array_keys($arr))) {
                                if ($v == 'ele_map' && is_array($val))
                                    $val = $this->GetWhere($val, true);

                                if ($tep == '?') { #正則
                                    $val = new MongoRegex($val);
                                    $wheres[$key] = $val;
                                } else {
                                    $wheres[$key][$arr[$tep]] = $val;
                                }
                            }
                        }
                    }
                } elseif (in_array($field, array_keys($maps_np))) {
                    if (in_array($field, array_keys($this->lgi_map)) && is_array($val)) { #邏輯
                        foreach ($val as $v) {
                            $val = $this->GetWhere($v, true);
                            $wheres[$maps_np[$field]][] = $val;
                        }

                    } else {
                        $wheres[$maps_np[$field]] = $val;
                    }
                } else { #普通查詢、單一條件內嵌文檔
                    if (strpos($field, "[") !== false)
                        $field = str_replace("[", ".", $field);

                    if (is_array($val) && $type) {
                        $arr = $this->GetWhere($val);
                        foreach ($arr as $k => $v) {
                            $wheres[$k][] = $v;
                        }
                    } elseif (is_null($val)) {
                        $wheres[$field] = array('$in' => array(null), '$exists' => 1);
                    } else {
                        $wheres[$field] = $val; #支持 array('age'=>array('>'=>'18','<='=>'20'))
                    }
                }
            }
        }

        return $wheres;
    }

    /**
     * 插入一行
     * @param $collect
     * @param $value
     * @return bool
     */
    public function InsOne($collect, $value)
    {
        if (!$this->collected || !is_array($value))
            return false;

        $id = array_search('id', array_keys($value)); #處理有id字段的情況
        if ($id !== false && array_search('_id', array_keys($value)) === false) {
            $value['_id'] = $value['id'];
            unset($value['id']);
        }

        $value = $this->ConvertEncode($value);
        if (!$value)
            return false;

        try {
            $result = $this->GetMonCollection($collect)->insert($value);
            $result = $result['err'] ? false : true;
        } catch (MongoException $e) {
            $this->ErrLog($e->getMessage());
            return false;
        }

        return $result;
    }

    /**
     * 插入多行
     * @param $collect 集合
     * @param $fields
     * @param $values 鍵值對:array(0=>array(''=>''))
     * @param bool $continueOnError 是否忽略插入錯誤,默認忽略
     * @return bool
     */
    public function InsMulit($collect, $fields, $values, $continueOnError = false)
    {
        if (!is_array($fields) || !is_array($values) || !$this->collected)
            return false;

        $id = array_search('id', $fields); #處理有id字段的情況
        if ($id !== false && array_search('_id', $fields) === false)
            $fields[$id] = '_id';

        $data = array();
        $values = $this->ConvertEncode($values);
        if ($values) {
            foreach ($values as $v) {
                if (is_array($v)) {
                    $v = array_combine($fields, $v);
                    if ($v)
                        $data[] = $v;
                }
            }
        }
        if (!$data)
            return false;

        $option['continueOnError'] = $continueOnError ? true : false;
        try {
            $result = $this->GetMonCollection($collect)->batchinsert($data, $option);
            $result = $result['err'] ? false : true;
        } catch (MongoException $e) {
            $this->ErrLog($e->getMessage());
            return false;
        }

        return $result;
    }

    /**
     * 查詢一個
     * @param $collect
     * @param array $where
     * @param $field string
     * @return bool
     */
    function FindOne($collect, $where = array(), $field)
    {
        if (!$this->collected)
            return false;

        $wheres = $this->GetWhere($where);
        if ($where && !$wheres)
            return false;

        if (is_string($field) && trim($field))
            $field = trim($field);
        else
            return false;

        $result = $this->GetMonCollection($collect)->findOne($wheres, array($field));

        if ($result) {
            $arr = get_object_vars($result['_id']);
            $result['_id'] = $arr['$id'];

            return $result[$field];
        }

        return false;
    }

    /**
     * 查詢一條
     * @param $collect
     * @param array|string $where
     * @param array $fields
     * @param string $type
     * @return array|bool
     */
    function FindRow($collect, $where = array(), $fields = array(), $type = 'assoc')
    {
        if (!$this->collected)
            return false;

        $wheres = $this->GetWhere($where);
        if ($where && !$wheres)
            return false;

        if ($fields && is_array($fields)) { #過濾fields
            $val = '';
            for ($i = 0; $i < count($fields); $i++) {
                $val[] = 1;
            }
            $fields = array_combine($fields, $val);
        } else {
            $fields = array();
        }

        $result = $this->GetMonCollection($collect)->findOne($wheres, $fields);

        if ($result) {
            if (in_array('_id', $fields)) {
                $arr = get_object_vars($result['_id']);
                $result['_id'] = $arr['$id'];
            } else {
                unset($result['_id']);
            }

            if (strtolower($type) == 'array')
                $result = array_values($result);

            return $result;
        }

        return false;
    }

    /**
     * 複合查詢  todo 查詢高級選項擴展 snapshot maxscan  min max hint explain
     * <-----------------------
     * $gt:>|$gte:>=|$le:<|$lte:<=|$ne:!=
     * array('x'=>array('$gt'=>'20'))
     *
     * $or:$|$end:&
     * array('x'=>array('$in'=>array('1','2')))
     *
     * $where:%
     * array('x'=>array('$where'=>function))
     *
     * 正則表達式:
     * ?
     *
     * 數組:
     * $all:*
     *
     * 內嵌文檔:
     * 單個條件:username.user   username[user
     * 多個條件:$elemMatch
     *
     * 邏輯操作符:
     * not:!
     * or:$
     * end:&
     * sort
     * array('x'=>0)
     *
     * limit|skip
     * $where = array('&|'=>array('she_hash' => '48b6c531ef2469469ede4ac21eebcf51', 'type' => 'doing'));
     * $field = array('time', '_id' => 0);
     * $res = $mongo->FindMix('sapilog', $where, $field,'1,2',array('time'=>'desc'));
     * ------------------------->
     * @param $collect |string
     * @param string $where |array array('>|x'=>'10','<=|x'=>'20','^|x'=>array(),'%|x'=>'fun')
     * @param array|string $fields |array|string 返回字段 默認爲全部 字符串返回一個字段,鍵爲數字則爲返回該字段,鍵爲字段,值爲-1爲不返回該字段
     * @param string $limit |string  skip,limit  0,10 如果沒有 默認 skip爲0 limit爲當前變量
     * @param string $sort |array array('x'=>'desc|asc') desc=>-1 asc=>
     * @param string $type  | string 返回類型 默認爲關聯數組 assoc|array
     * @return bool
     */
    public function FindMix($collect, $where = '', $fields = array(), $limit = '', $sort = '', $type = 'assoc')
    {
        if (!$this->collected)
            return false;

        $wheres = $this->GetWhere($where);
        if ($where && !$wheres)
            return false;

        if ($fields && is_array($fields)) { #過濾fields
            $val = '';
            for ($i = 0; $i < count($fields); $i++) {
                $val[] = 1;
            }
            $fields = array_combine($fields, $val);
        } else {
            $fields = array();
        }

        $limits = '';
        $skip = '';
        if (is_string($limit)) { #過濾limit
            $limit = explode(",", trim($limit));
            if ($limit && is_numeric(implode('', $limit))) {
                if (count($limit) == 1) {
                    $limits = $limit[0];
                } else {
                    $skip = $limit[0];
                    $limits = $limit[1];
                }
            }
        } elseif (is_numeric($limit)) {
            $limits = trim($limit);
        }

        $sorts = '';
        if (is_array($sort) && $sort) { #過濾sort
            foreach ($sort as $k => $v) {
                $k = trim($k);
                $v = strtoupper(trim($v));
                if (in_array($v, array_keys($this->sort_map))) {
                    $sorts[$k] = $this->sort_map[$v];
                }
            }
        }

        $result = $this->GetMonCollection($collect)->find($wheres, $fields);
        if ($skip)
            $result = $result->skip($skip);
        if ($limits)
            $result = $result->limit($limits);
        if ($sorts)
            $result = $result->sort($sorts);

        if ($result) {
            $return = array();
            foreach ($result as $v) {
                $return[] = $v;
            }
            foreach ($return as &$v) {
                if (in_array('_id', $fields)) {
                    $arr = get_object_vars($v['_id']);
                    $v['_id'] = $arr['$id'];
                } else {
                    unset($v['_id']);
                }

                if (strtolower($type) == 'array')
                    $v = array_values($v);
            }

            return $return;
        }

        return false;
    }

    /**
     * 修改記錄
     * $inc、$set、$unset 修改普通文檔,如果有就修改,沒有就條件加值創建,前者只支持數字類型,使用後者,$unset刪除元素
     * $push、$addToSet 添加數組元素,前者不去重,使用後者
     * $pop、$pull 刪除數組元素,前者刪除前後,後者刪除指定元素,使用後者
     *
     * @param $collect
     * @param $where
     * @param $newdata |array
     * @param string $type   操作類型 upd修改 unset刪除指定元素 arr修改數組元素 pull刪除數組元素
     * @param bool $upsert 是否創建
     * @param int $return |1:返回bool,2:返回影響行數
     * @return bool
     */
    public function UpdMix($collect, $where, $newdata, $type = 'upd', $upsert = false, $return = 1)
    {
        if (!$this->collected || !is_array($newdata))
            return false;

        $wheres = $this->GetWhere($where);
        if (!$wheres) {
            $this->ErrLog('where is error');
            return false;
        }

        $newdata = $this->ConvertEncode($newdata);

        $type = strtolower(trim($type));
        $types = array('upd' => '$set', 'unset' => '$unset', 'arr' => '$addToSet', 'pull' => '$pull');
        if (isset($types[$type])) {
            $option = array();
            if ($type == 'upd')
                $option = array('multiple' => true);
            if (in_array($type, array('upd', 'arr')) && $upsert)
                $option['upsert'] = true;

            $newdata = array($types[$type] => $newdata);
        } else {
            return false;
        }

        try {
            $result = $this->GetMonCollection($collect)->update($wheres, $newdata, $option);
            $result = $return == 1 ? ($result['err'] ? false : true) : $result['n'];
        } catch (MongoConnectionException $e) {
            $this->ErrLog($e->getMessage());
            return false;
        }

        return $result;
    }

    #todo EXPLAIN 函數

    /**
     * 對集合執行命令
     * @param $data
     * @return bool
     */
    public function RunCommand($data)
    {
        if (is_array($data) && $data && $this->collected) {
            $result = $this->db->command($data);

            if (isset($result['values']))
                return $result['values'];
            else
                $this->ErrLog("command error,info:" . $result['errmsg'] . ",bad_cmd:" . json_encode($result['bad cmd']));

        }
        return false;
    }

    /**
     * todo 聚合
     *
     */
    public function Group()
    {

    }

    public function Count($collect, $where = array())
    {
        if (!$this->collected)
            return false;

        $wheres = $this->GetWhere($where);
        if ($where && !$wheres)
            return false;

        return $this->GetMonCollection($collect)->count($wheres);
    }

    /**
     * 返回指定鍵的唯一值列表
     * @param $collect
     * @param $key
     * @param array $where 額外查詢條件
     * @return bool
     */
    public function Distinct($collect, $key, $where = array())
    {
        if (!$this->collected)
            return false;

        $wheres = $this->GetWhere($where);
        if ($where && !$wheres)
            return false;

        try {
            $result = $this->GetMonCollection($collect)->distinct($key, $wheres);
        } catch (MongoException $e) {
            $this->ErrLog($e->getMessage());
            return false;
        }

        return $result;
    }

    /**
     * 刪除集合中的記錄
     * @param $collect
     * @param $where
     * @param int $return 1:返回bool,2:返回影響行數
     * @return bool
     */
    public function RemoveColl($collect, $where, $return = 1)
    {
        if (!$this->collected)
            return false;

        $wheres = $this->GetWhere($where);
        if (!$wheres) {
            $this->ErrLog('where is error');
            return false;
        }

        try {
            $result = $this->GetMonCollection($collect)->remove($wheres);
            $result = $return == 1 ? ($result['err'] ? false : true) : $result['n'];
        } catch (MongoConnectionException $e) {
            $this->ErrLog($e->getMessage());
            return false;
        }

        return $result;
    }

    /**
     * mongo 錯誤日誌函數
     *
     * @param $msg
     * @param int $lever
     *
     */
    private function ErrLog($msg, $lever = 2)
    {
        global $__CFG;

        $trace = debug_backtrace();
        $error_log = '';
        $date = date("Ymd", time());

        $line = isset($trace[$lever]['line']) ? trim($trace[$lever]['line']) : '';
        $file = isset($trace[$lever]['file']) ? trim($trace[$lever]['file']) : '';

        $object = isset($trace[$lever]['object']) ? get_class($trace[$lever]['object']) : '';
        $args = isset($trace[$lever]['args']) ? json_encode($trace[$lever]['args']) : '';

        $error_log .= "line {$line} " . ($object ? 'of ' . $object : '') . "(in {$file})\n";
        $error_log .= $args ? "args:{$args}\n" : '';
        $error_log .= "msg:{$msg}";


        if (isset($__CFG['com']['id']) && $__CFG['com']['id']) {
            $com_id = $__CFG['com']['id'];
        } else {
            $com_id = 'common';
        }

        $log_dir = $this->config['logpath'] ? $this->config['logpath'] : __ROOT__ . "data/nginx_error_log/{$com_id}/{$date}/mongo.nginx_error_log";
        error_log("Date:" . date("Y-m-d H:i:s", $date) . "\nstamp:{$date}\ntrace:{$error_log}\n\n", 3, $log_dir);

        if (isset($__CFG['currUser']) && $__CFG['currUser'] == 'root' && isset($__CFG['daemon']['user'])) {
            $paths = explode("nginx_error_log/", $log_dir);
            $pathc = explode("/", $paths[1]);
            $pathd = $paths[0] . "nginx_error_log";
            foreach ($pathc as $v) {
                $pathd .= "/" . $v;
                chgrp($pathd, $__CFG['daemon']['user']);
                chown($pathd, $__CFG['daemon']['user']);
            }
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章