Authored by ziy

添加DB的Mongo方法,

1、修改分页
2、查询接口
... ... @@ -8,7 +8,7 @@
namespace Hood\Dao\MongoDB;
class Collection
class Collection extends Cursor
{
/**
... ... @@ -24,21 +24,10 @@ class Collection
private $_dbName;
/**
* @var \MongoCollection
*/
private $_collection;
/**
* 条件
* @var array
*/
private $_attrs = array();
/**
* 返回的结果集
* @var array
*/
private $fields = array();
private $_fields = array();
/**
* @var string
... ... @@ -67,11 +56,7 @@ class Collection
$result->status = $bool = $this->_collection->insert($attrs, $options);
$result->attrs = $attrs;
if ($bool) {
if ($attrs["_id"] instanceof \MongoId) {
$result->_id = $attrs["_id"]->__toString();
} else {
$result->_id = $attrs["_id"];
}
$result->_id = $attrs["_id"];
}
return $result;
}
... ... @@ -84,15 +69,16 @@ class Collection
*/
public function find(array $query = array(), array $fields = array())
{
$_results = $this->_collection->find($query, $fields);
$rets = array();
foreach ($_results as $value) {
if (isset($value["_id"]) && ($value["_id"] instanceof \MongoId)) {
$value["_id"] = $value["_id"]->__toString();
}
$rets[] = $value;
}
return $rets;
return $this->_collection->find($query, $fields);
}
/**
* 查询所有符合条件的数据
* @return \MongoCursor
*/
public function findAll()
{
return $this->_cursor();
}
/**
... ... @@ -103,12 +89,8 @@ class Collection
*/
public function findOne(array $query = array(), array $fields = array())
{
$_fields = empty($fields) ? $this->fields : $fields;
$_results = $this->_collection->findOne($query, $_fields);
if (isset($_results["_id"]) && ($_results["_id"] instanceof \MongoId)) {
$_results["_id"] = $_results["_id"]->__toString();
}
return $_results;
$_fields = empty($fields) ? $this->_fields : $fields;
return $this->_collection->findOne($query, $_fields);
}
/**
... ... @@ -118,33 +100,11 @@ class Collection
*/
public function fields(array $fields)
{
$this->fields = $fields;
$this->_fields = $fields;
return $this;
}
/**
* 组合查询条件
* @return array
*/
private function criteria()
{
$attrs = $this->_attrs;
foreach ($this->_attrs as $attr => $values) {
if (!empty($values)) {
if (count($values) == 1) {
$attrs[$attr] = $values[0];
} else {
$attrs[$attr]['$in'] = $values;
}
}
}
foreach ($this->_conds as $key => $value) {
$attrs[$key] = $value;
}
return $attrs;
}
/**
* 更新
* @param array $criteria
* @param array $newobj
... ... @@ -182,9 +142,58 @@ class Collection
* @param $id
* @return array|null
*/
function findID($id, array $fields = array())
public function findID($id, array $fields = array())
{
$_fields = empty($fields) ? $this->_fields : $fields;
if (($id instanceof \MongoId) == false) {
$id = new \MongoId($id);
}
return $this->_collection->findOne(array('_id' => $id), $_fields);
}
/**
* 保存一个文档到集合
* 如果对象来自数据库,则更新现有的数据库对象,否则插入对象
* @param $a
* @param array $options
* @return array|bool
*/
public function save($a, array $options = array())
{
return $this->_collection->save($a, $options);
}
/**
* 查询并更新数据
* @param array $query
* @param array $update
* @param array $fields
* @param array $options
* @return array
*/
public function findAndModify(array $query, array $update = NULL, array $fields = NULL, array $options = NULL)
{
return $this->_collection->findAndModify($query, $update, $fields, $options);
}
/**
* 获取总数
* @param array $query
* @return int
*/
public function count($query = array())
{
return $this->_collection->count($query);
}
/**
* 批量插入一组新的数据
* @param array $a
* @param array $options
* @return mixed
*/
public function batchInsert(array $a, array $options = array())
{
$_fields = empty($fields) ? $this->fields : $fields;
return $this->_collection->findOne(array('_id' => new \MongoId($id)), $_fields);
return $this->_collection->batchInsert($a, $options);
}
}
\ No newline at end of file
... ...
... ... @@ -9,6 +9,135 @@
namespace Hood\Dao\MongoDB;
class Cursor {
class Cursor
{
/**
* @var \MongoCursor
*/
protected $_cursor;
/**
* @var \MongoCollection
*/
protected $_collection;
/**
* 条件
* @var array
*/
protected $_attrs = array();
protected $_conds = array();
protected $_offset = -1;
protected $_limit = 0;
protected $_sort = array();
protected $_hints = array();
protected $_results = array();
protected function _cursor()
{
$cursor = $this->_collection->find($this->criteria(), $this->_results);
if ($this->_offset >= 0) {
$cursor->skip($this->_offset);
}
if ($this->_limit > 0) {
$cursor->limit($this->_limit);
}
if ($this->_sort) {
$cursor->sort($this->_sort);
}
if (!empty($this->_hints)) {
foreach ($this->_hints as $hint) {
$cursor->hint($hint);
}
}
return $cursor;
}
/**
* 组合查询条件
* @return array
*/
private function criteria()
{
$attrs = $this->_attrs;
foreach ($this->_attrs as $attr => $values) {
if (!empty($values)) {
if (count($values) == 1) {
$attrs[$attr] = $values[0];
} else {
$attrs[$attr]['$in'] = $values;
}
}
}
foreach ($this->_conds as $key => $value) {
$attrs[$key] = $value;
}
return $attrs;
}
public function offset($num)
{
$this->_offset = (int)$num;
return $this;
}
public function limit($num)
{
$this->_limit = (int)$num;
return $this;
}
public function skip($num)
{
$this->_offset = (int)$num;
return $this;
}
public function sort(array $fields)
{
foreach ($fields as $key => $val) {
if (is_string($key)) {
$this->_sort[$key] = $val;
}
}
return $this;
}
/**
* 设置正排序条件
*
* @param string $attr 需要排序的属性
* @return $this
*/
public function asc($attr = "_id")
{
$this->_sort[$attr] = 1;
return $this;
}
/**
* 设置倒排序条件
*
* @param string $attr 需要排序的属性
* @return $this
*/
public function desc($attr = "_id")
{
$this->_sort[$attr] = -1;
return $this;
}
public function hint($hint)
{
$this->_hints[] = $hint;
return $this;
}
}
\ No newline at end of file
... ...
<?php
/**
* Created by PhpStorm.
* User: Zip
* Date: 15/6/10
* Time: 下午11:51
*/
abstract class MongoPage
{
private $keyword;
private $total;
private $path;
private $size;
private $properties;
private $query;
private $length;
private $pageSetSize = 11;
private $rows = array();
/**
* 是否加载了本地化对象
*
* @var boolean
* @since 1.0
*/
private $localeLoaded = false;
/**
* 语言配置
*
* @var array
* @since 1.0
*/
private $messages = array();
/**
* 分页中代码当前页码的常量
*
*/
const PAGER_VARIABLE_STRING = "%{PAGE_NO}";
/**
* 构造器
*
* @since 2.0
*/
function __construct()
{
$this->path = $_SERVER["PHP_SELF"];
}
/**
* 取得当前页码,第一页为1
*
* @return integer
*/
function current()
{
$keyword = $this->keyword();
$pageNo = intval(x($keyword));
if ($pageNo <= 0) {
$pageNo = 1;
}
return min($pageNo, $this->length());
}
/**
* 取得下一页页码
*
* @return integer
*/
function next()
{
$length = $this->length();
$current = $this->current();
return $current < $length ? ($current + 1) : $length;
}
/**
* 取得上一页页码
*
* @return integer
*/
function prev()
{
$length = $this->length();
$current = $this->current();
return $current > 1 ? ($current - 1) : 1;
}
/**
* 取得记录开始的偏移量
*
* @return integer
*/
function offset()
{
$offset = $this->size() * ($this->current() - 1);
if ($offset < 0) {
$offset = 0;
}
if ($offset >= $this->total()) {
$offset = max($this->size() * ($this->length() - 1), 0);
}
return $offset;
}
/**
* 设置内容总数
*
* @param integer $total 内容总数
* @return MongoPage
*/
function setTotal($total)
{
$this->total = intval($total);
if ($this->total < 0) {
throw new \Exception("content total '{$total}' can't be small than 0");
}
return $this;
}
/**
* 数据总数
*
* @return integer
* @since 1.0
*/
function total()
{
return $this->total;
}
/**
* 设置分页链接中的关键字
*
* @param string $keyword 关键字
* @return MongoPage
*/
function setKeyword($keyword)
{
$this->keyword = $keyword;
return $this;
}
/**
* 取得分页用的关键字
*
* 从1.0开始,如果没有关键字,则默认为page
*
* @return string
*/
function keyword()
{
if (!$this->keyword) {
$this->keyword = "page";
}
return $this->keyword;
}
/**
* 设置每页记录数
*
* @param integer $size 大于0的数字
* @return MongoPage
*/
function setSize($size)
{
$this->size = intval($size);
if ($this->size < 1) {
throw new \Exception("page size '{$size}' can't be small than 1");
}
return $this;
}
/**
* 取得每页记录数
*
* @return integer
*/
function size()
{
if ($this->size < 1) {
$this->size = 10;
}
return $this->size;
}
/**
* 设置链接的路径
*
* @param string $path 路径
* @return MongoPage
*/
function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* 取得程序路径
*
* @return string
* @since 1.0
*/
function path()
{
return $this->path;
}
/**
* 设置属性
*
* @param array $properties 属性列表
* @return MongoPage
*/
function setProperties(array $properties)
{
$this->properties = $properties;
return $this;
}
/**
* 取得设置的属性
*
* @return array
* @since 1.0
*/
function properties()
{
return $this->properties;
}
/**
* 设置查询
*
* @param mixed $query string|array
* @return MongoPage
*/
function setQuery($query)
{
if (is_array($query)) {
$_query = array();
foreach ($query as $key => $value) {
if ($key == $this->keyword()) {
continue;
}
if (is_array($value)) {
foreach ($value as $key1 => $value1) {
$_query[] = "{$key}[]=" . urlencode($value1);
}
} else {
$_query[] = "{$key}=" . urlencode($value);
}
}
$query = implode("&", $_query);
}
$this->query = $query;
return $this;
}
/**
* 添加查询条件
*
* <code>
* $page->addQuery(array(
* "e" => 5,
* "f" => 6
* ));
* $page->addQuery("g=7");
* </code>
*
* @param mixed $query string|array
* @return MongoPage
*/
function addQuery($query)
{
if (is_array($query)) {
$_query = array();
foreach ($query as $key => $value) {
if ($key == $this->keyword()) {
continue;
}
if (is_array($value)) {
foreach ($value as $key1 => $value1) {
$_query[] = "{$key}[]=" . urlencode($value1);
}
} else {
$_query[] = "{$key}=" . urlencode($value);
}
}
$query = implode("&", $_query);
}
$this->query .= ($this->query ? "&" : "") . $query;
return $this;
}
/**
* 开启自动构造查询条件功能
*
* @param boolean $bool 是否开启该功能
* @param string|array $except 要去除的参数名
* @param string|array $only 限制的参数名
* @return MongoPage
*/
function setAutoQuery($bool = true, $except = "", $only = "")
{
if (!is_array($except)) {
$except = preg_split("/\\s+,\\s+/", $except);
}
if (!is_array($only) && strlen($only) > 0) {
$only = preg_split("/\\s+,\\s+/", $only);
}
if ($bool) {
$x = xn();
foreach ($x as $name => $value) {
if ($except && in_array($name, $except)) {
unset($x[$name]);
}
if ($only && !in_array($name, $only)) {
unset($x[$name]);
}
}
$this->setQuery($x);
}
return $this;
}
/**
* 取得查询
*
* @return array
* @since 1.0
*/
function query()
{
return $this->query;
}
/**
* 取得一个分页好号对应的URL
*
* @param integer $pageNo 分页号
* @return string
* @since 1.0
*/
function url($pageNo)
{
$query = $this->query();
if (strstr($query, self::PAGER_VARIABLE_STRING)) {
$query = str_replace(self::PAGER_VARIABLE_STRING, $pageNo, $query);
} else {
if ($query == "") {
$query = $this->keyword() . "=" . $pageNo;
} else {
$query .= "&" . $this->keyword() . "=" . $pageNo;
}
}
return $this->path() . "?" . $query;
}
/**
* 取得总分页数
*
* @return integer
* @since 1.0
*/
function length()
{
if ($this->size() == 0) {
return 0;
}
return ceil($this->total() / $this->size());
}
/**
* 添加记录
*
* @param mixed $row 记录
* @return MongoPage
*/
function addRow($row)
{
$this->rows[] = $row;
return $this;
}
/**
* 添加记录集
*
* @param array $rows 记录集
* @return MongoPage
*/
function addRows(array $rows)
{
foreach ($rows as $row) {
$this->rows[] = $row;
}
return $this;
}
/**
* 取得记录集
*
* @return array
*/
function rows()
{
return $this->rows;
}
/**
* 设置记录集
*
* @param array|iterable $rows 记录集
* @return MongoPage
*/
function setRows($rows)
{
$this->rows = $rows;
return $this;
}
/**
* 取得键值对应的消息文本
*
* @param string $key 键值
* @return string
* @since 1.0
*/
protected function message($key)
{
if (!$this->localeLoaded) {
$locale = __LANG__;
if (!$locale) {
$locale = "default";
}
$message = x("~" . $key);
if ($message) {
return $message;
}
//简写
$dirname = dirname(__FILE__) . "/lang";
$langFile = $dirname . "/" . $locale . ".php";
if (is_file($langFile)) {
require($langFile);
$this->messages = $message;
}
$this->localeLoaded = true;
}
if (is_array($this->messages) && array_key_exists($key, $this->messages)) {
return $this->messages[$key];
}
return null;
}
/**
* 转换成字符串
*
* @return string
*/
public abstract function __toString();
/**
* 设置分页集尺寸
*
* @param integer $num 大于1
* @return MongoPage
* @since 1.0
*/
function setPageSetNum($num)
{
$this->pageSetSize = $num;
return $this;
}
/**
* 取得分页集尺寸
*
* @return integer
* @since 1.0
*/
function pageSetNum()
{
return $this->pageSetSize;
}
static function pageWithStyle($style, array $params = null)
{
exit(__METHOD__ . " need to be implemented.");
}
}
\ No newline at end of file
... ...
### 插入数据
```php
DB::Mongo()->selectCollection('loggers','coupons')->insert(array('a'=>1));
```
### 添加数据并获取添加数据和返回的数据
```php
$attrs = DB::Mongo()->collection('loggers','coupons')->insert(array('a'=>1))->getAttrs();
```
### 添加数据并获取状态
```php
$status = DB::Mongo()->collection('loggers','coupons')->insert(array('a'=>1))->getStatus();
```
###添加数据并获取插入的ID
```php
$id = DB::Mongo()->collection('loggers','coupons')->insert(array('a'=>1))->lastInsertId();
```
###分页显示
```php
$data = DB::Mongo()->collection('loggers', 'coupons')->offset(1)->limit(2)->findAll();
```
###获取总数
```php
$data = DB::Mongo()->collection('loggers', 'coupons')->count(array('a'=1));
```
###查询所有数据
```php
SQL等于 select * from loggers.coupons
$data = DB::Mongo()->collection('loggers', 'coupons')->find();
```
###查询所有符合条件数据
```php
SQL等于 select a from loggers.coupons where a=1
$data = DB::Mongo()->collection('loggers', 'coupons')->find(array('a' => 1), array('a'));
foreach ($data as $key => $val) {
print_r($val);
}
#SQL 等于 select a from loggers.coupons where a=1 or a=2
#$data = DB::Mongo()->collection('loggers', 'coupons')->find(array('$or' => array(array('a' => 1), array('a' => 2))), array('a'));
SQL 等于 select a from loggers.coupons where a=1 or a=2
$data = DB::Mongo()->collection('loggers', 'coupons')->find(array('$or' => array(array('a' => 1), array('a' => 2))), array('a'));
#SQL 等于 select log_type from loggers.coupons where id='554ab308becb29dd820041a9'
#$data = DB::Mongo()->collection('loggers', 'coupons')->findOne(array('_id' => new \MongoId('554ab308becb29dd820041a9')), array('log_type'));
SQL 等于 select log_type from loggers.coupons where id='554ab308becb29dd820041a9'
$data = DB::Mongo()->collection('loggers', 'coupons')->findOne(array('_id' => new \MongoId('554ab308becb29dd820041a9')), array('log_type'));
#查询ID
#$data = DB::Mongo()->collection('loggers', 'coupons')->findID('554ab308becb29dd820041a9');
查询ID
$data = DB::Mongo()->collection('loggers', 'coupons')->findID('554ab308becb29dd820041a9');
```
###更新
#更新a=3的数据为name="YOHO"
#$data = DB::Mongo()->collection('loggers', 'coupons')->update(array('a' => 3), array('name' => "YOHO"));
```php
更新a=3的数据为name="YOHO"
$data = DB::Mongo()->collection('loggers', 'coupons')->update(array('a' => 3), array('name' => "YOHO"));
#SQL 等于 update loggers.coupons set test1='Mongo1' where test='Mongo'
#$data = DB::Mongo()->collection('loggers', 'coupons')->set()->update(array('test' => "Mongo"), array("test1" => "Mongo1"));
SQL 等于 update loggers.coupons set test1='Mongo1' where test='Mongo'
$data = DB::Mongo()->collection('loggers', 'coupons')->set()->update(array('test' => "Mongo"), array("test1" => "Mongo1"));
```
###删除
#SQL 等于 delete from loggers.coupons where _id='55795b4cbecb297f610041a7'
#$data = DB::Mongo()->collection('loggers', 'coupons')->remove(array('_id' => new \MongoId('55795b4cbecb297f610041a7')));
\ No newline at end of file
```php
SQL 等于 delete from loggers.coupons where _id='55795b4cbecb297f610041a7'
$data = DB::Mongo()->collection('loggers', 'coupons')->remove(array('_id' => new \MongoId('55795b4cbecb297f610041a7')));
```
###save
```php
$mo = DB::Mongo()->collection('loggers', 'coupons');
$data = array('a' => 1, 'b' => 2);
$mo->insert($data);
$data['c'] = 1;
$data = $mo->save($data);
$mo = DB::Mongo()->collection('loggers', 'coupons');
$data = $mo->find();
foreach ($data as $val) {
$val['yoho1'] = 'Me';
$mo->save($val);
}
```
\ No newline at end of file
... ...