php 封装mongodb及调用

分为两个文件,
第一个文件主要用于数据库连接
第二个文件用于具体mongo的操作封装

直接上代码:

1.Common/Custom/Db/Mongo.class.php

<?php
namespace Common\Custom\Db;

/**
 * mongo
 *
 * @return   void
 **/
class Mongo
{
    
    static $db = null;
    private function __construct($params)
    {
        if (!class_exists('Mongo')) {
            exit('请安装mongo插件');
        }

        try {
            $this->_getMongoClient($params);
        } catch(\Exception $e) {
            exit('连接mongo失败');
        }
    }

    /**
     * 获取实例
     *
     * @param    array
     *
     * @return   object
     **/
    static public function getInstance($params = array())
    {
        if (empty(self::$db[$params['db']])) {
            self::$db[$params['db']] = new self($params);
            self::$db['db_name']     = $params['db'];
        }

        return self::$db[$params['db']];
    }

    /**
     * 连接mongo
     *
     * @param    array
     *
     * @return   object
     **/
    private function _getMongoClient($params,$retry = 3)
    {
        try {
            if(isset($params['host'])){
                $this->_mongo_db = new \Mongo($params['host'], array("timeout" => -1));
            }else{
                $this->_mongo_db = new \Mongo(C('MONGO_HOST').':'.C('MONGO_PORT'), array("timeout" => -1));
            }
            $report_db_array  = C('MONGO_DB');
            $this->_sanger_db = $this->_mongo_db->$report_db_array[$params['db']];
            $this->_db_name   = $report_db_array[$params['db']];
            return;
        } catch(\Exception $e) {
        }

        if ($retry > 0) {
            return $this->_getMongoClient($params, --$retry);
        }

        throw new \Exception('尝试3次连接失败');
    }

    /**
     * 选择表格
     *
     * @param    array
     *
     * @return   object
     **/
    public function selectTable($table_name)
    {
        return \Common\Custom\Db\Driver\Mongo::getInstance($table_name, $this->_sanger_db, $this->_db_name);
    }



    /**
     * 返回错误
     *
     * @return   string
     **/
    public function getError()
    {
        return $this->_error;
    }
    
}

2.Common/Custom/Db/Driver/Mongo.class.php(mongo具体封装操作层)

// Driver/Mongo.class.php

<?php
namespace Common\Custom\Db\Driver;

/**
 * mongo
 *
 * @return   void
 **/
class Mongo
{
    private static $_db_array = array();
    private $_params          = array('skip' => null, 'limit' => null);
    
    private function __construct($table_name, $db)
    {
        $this->_table_name = $table_name;
        $this->_db         = $db;
    }

    /**
     * 获取实例
     *
     * @param    string
     * @param    array
     *
     * @return   object
     **/
    static function getInstance($table_name, $db, $db_name)
    {
        $link_id = md5($table_name.'_'.$db_name);
        if (empty(self::$_db_array[$link_id])) {
            self::$_db_array[$link_id] = new self($table_name, $db);
        }

        return self::$_db_array[$link_id];
    }

    /**
     * 排序
     *
     * @param    string
     *
     * @return   object
     **/
    public function sort($params)
    {
        $this->_params['sort'] = $params;
        return $this;
    }

    /**
     * 分页
     *
     * @param    string
     *
     * @return   object
     **/
    public function limit($limit)
    {
        $this->_params['limit'] = $limit;
        return $this;
    }

    /**
     * 分页
     *
     * @param    string
     *
     * @return   object
     **/
    public function skip($skip)
    {
        $this->_params['skip'] = $skip;
        return $this;
    }

    /**
     * 获取字段
     *
     * @param    string
     *
     * @return   object
     **/
    public function field($field)
    {
        $this->_params['field'] = $field;

        return $this;
    }

    /**
     * 查询
     *
     * @param    array
     *
     * @return   array
     **/
    public function find($_condition)
    {
       ini_set('mongo.long_as_object', 1);
        $table_name = $this->_table_name;
        $table      = $this->_db->$table_name;
        if (empty($_condition)) {
            $this->cursor = $table->find();
        } else {
            $this->cursor = $table->find($_condition);
        }
        $this->cursor->timeout(-1);
        
        if ($this->_params['sort']) {
            $this->cursor->sort($this->_params['sort']);
        }

        if ($this->_params['limit'] !== null) {
            $this->cursor->limit($this->_params['limit']);
        }

        if ($this->_params['skip']) {
            $this->cursor->skip($this->_params['skip']);
        }

        if (!$this->cursor->count()) {
            return array();
        }

        $infos = array();
        $i = 0;
        foreach ($this->cursor as $val) {
            if ($this->_params['field']) {
                foreach ($this->_params['field'] as $key => $field) {
                    if (is_string($key)) {
                        $infos[$i][$key] = is_object($val[$field]) ? strval($val[$field]) : $val[$field];
                        continue;
                    }
                    $infos[$i][$field] = is_object($val[$field]) ? strval($val[$field]) : $val[$field];
                }
            } else {
                $infos[$i] = $val;
            }

            $i ++;
        }

        $this->_params = array('skip' => null, 'limit' => null);
        unset($this->cursor);
        
        return $infos;
    }

    /**
     * 查找数据
     *
     * @param    array
     *
     * @return   array
     **/
    public function findOne($params)
    {
        ini_set('mongo.long_as_object', 1);    
        $table_name = $this->_table_name;
        $table      = $this->_db->$table_name;
        $info = $table->findOne($params);
        if (empty($this->_params['field'])) {
            return $info;
        }
        $result_info = array();
        foreach ($this->_params['field'] as $key => $field) {
            if (is_string($key)) {
                $result_info[$key] = is_object($info[$field]) ? strval($info[$field]) : $info[$field];
                continue;
            }
            $result_info[$field] = is_object($info[$field]) ? strval($info[$field]) : $info[$field];
        }

        unset($info);

        return $result_info;
    }

    /**
     * 统计数量
     *
     * @param    array
     *
     * @return   int
     **/
    public function count($params)
    {
        ini_set('mongo.long_as_object', 1);
        $table_name = $this->_table_name;
        $table      = $this->_db->$table_name;
        return $table->count($params);
    }

    /**
     * 插入数据
     *
     * @param    array
     *
     * @return   array
     **/
    public function insert($params)
    {
        $table_name = $this->_table_name;
        $table      = $this->_db->$table_name;
        $result = $table->insert($params);
        if ($result) {
            return strval($params['_id']);
        }

        return false;
    }
    
    
    /**
     * 插入32位数据
     *
     * @param    array
     *
     * @return   array
     **/
    public function insert32($params)
    {
        ini_set('mongo.native_long', 0);
        $table_name = $this->_table_name;
        $table      = $this->_db->$table_name;
        $result = $table->insert($params);
        if ($result) {
            return strval($params['_id']);
        }
    
        return false;
    }

    /**
     * 删除一条数据
     *
     * @param    array
     *
     * @return   array
     **/
    public function deleteOne($params)
    {
        $table_name = $this->_table_name;
        $table      = $this->_db->$table_name;

        return $table->remove($params,array("justOne" => true));
    }
    
    /**
     * 统计去重后的数量
     *
     * @param    array
     *
     * @return   int
     **/
    public function distinctCount($key, $params)
    {
        $table_name = $this->_table_name;
        $table      = $this->_db->$table_name;
        return count($table->distinct($key, $params));
    }

    /**
     * 去重后的列表
     *
     * @param    array
     *
     * @return   int
     **/
    public function distinct($key, $params)
    {
        $table_name = $this->_table_name;
        $table      = $this->_db->$table_name;
        return $table->distinct($key, $params);
    }

    /**
     * 统计数量
     *
     * @param    array
     *
     * @return   int
     **/
    public function group($keys, $initial, $reduce) {
        $table_name = $this->_table_name;
        $table      = $this->_db->$table_name;
        
        $g = $table->group($keys, $initial, $reduce);
        
        return $g['retval'];
    }
    
    /**
     * 更新
     * 
     * @param    array
     * @param    array
     * 
     */
    public function update($params, $update)
    {
        $table_name = $this->_table_name;
        $table      = $this->_db->$table_name;
        $info = $table->update($params, $update);
        return $info;
    }
    
    /**
     * 更新并增加一条记录
     *
     * @param    array
     * @param    array
     *
     */
    public function upsert($params, $update)
    {
        $table_name = $this->_table_name;
        $table      = $this->_db->$table_name;
        $info = $table->update($params, $update, array('upsert'=>true));
        return $info;
    }
    
    
    /**
     * 批量插入数据
     *
     * @param    array
     *
     * @return   array
     **/
    public function batchInsert($params)
    {
        if (empty($params)) {
            $this->_error = '参数为空';
            return false;
        }
        $table_name = $this->_table_name;
        $table      = $this->_db->$table_name;
        $result = $table->batchInsert($params);
    }
	
	/**
     * 批量插入数据
     *
     * @param    array
     *
     * @return   array
     **/
    public function batchInsert32($params)
    {
        ini_set('mongo.native_long', 0);
        if (empty($params)) {
            $this->_error = '参数为空';
            return false;
        }
        $table_name = $this->_table_name;
        $table      = $this->_db->$table_name;
        $result = $table->batchInsert($params);
    }

    /**
     * 删除表格
     *
     * @param    array
     *
     * @return   array
     **/
    public function dropTable()
    {
        $table_name = $this->_table_name;
        $table      = $this->_db->$table_name;

        return $table->drop();
    }

    /**
     * 返回错误
     *
     * @return   string
     **/
    public function getError()
    {
        return $this->_error;
    }
    
}

结合到业务层的调用操作:
 

 //初始化示例并制定调用project_db,project_db是在config.php里面定义好的一个指向数据库名称的key
 $sanger_db = \Common\Custom\MongoTest::getInstance(array('db' => 'project_db'));

 //选择对应的表
 $log_operate_db  = $sanger_db->selectTable('sg_log_operate');
    
 单条数据:
 $info = $log_operate_db->field(array('log_id' => '_id', 'from_id', 'time'))->findOne(array('_id' => new \MongoId('58ec93d5dde3eed81100002b')));
 多条数据查询:
 $infos = $log_operate_db->field($field)->sort(array('time' => -1))->limit($params['limit'])->skip($params['skip'])->find($_condition);

 插入数据
$result = $log_operate_db->insert($params);
 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值