之前写过mysql篇的orm,以后将整合到一个目录里面去。本文针对mongodb也写一篇,仅学习使用,初稿,并将逐步完善,代码如下
Db类
namespace phporm;
abstract class Db{
//静态对象
protected static $selfObj = null;
//数据库连接池
protected $conn;
//sql语句
protected $sql;
//最后生成的sql
protected $lastSql = null;
//日志目录
protected $logDir = './log/';
//日志开关
protected $logOpen = true;
//调试模式
protected $debug = false;
//错误提示(不开启调试模式时使用)
protected $errorTip = 'Params Error';
//选择需要操作的表,这里指集合
protected $table;
//记录表结构信息
protected $describe = [];
//主键
protected $pk = '';
//数据库
protected $database = '';
//表别名
protected $alias = '';
//设置排序参数
protected $orderParam = '';
//设置查询字段
protected $fieldParam = '*';
//查询条件参数
protected $whereParam;
//条件参数数组
protected $whereParamArray = [];
//允许查询条数
protected $limitParam = '';
//分组字段参数
protected $groupParam = '';
//链表参数
protected $joinParam = '';
//数据参数
protected $dataParam = [];
//更新参数
protected $updateParam = '';
//生成sql而不执行
protected $fetchSql = false;
//数据库链接信息
protected $connectInfo = [
'host' => '127.0.0.1',
'user' => 'root',
'password' => 'root',
'port' => 27017,
'database' => 'test',
'prefix' => '',
'charset' => 'uft8mb4'
];
abstract public function connect(array $connect = []);
/**
* 抛出错误
* @author jinanav 2020年7月24日22:26:15
* @param string $errorInfo 连接参数
* @return $this;
*/
public function error($errorInfo = null){
if(!empty($errorInfo)) exit($errorInfo);
exit($this->errorTip);
}
}
mongo类
namespace phporm\mongodb;
use phporm\Db;
/**
* Class Mongo mongodb操作类
*/
class Mongo extends Db {
//查询配置项
private $options = [];
//集合
private $collection = '';
//mongodb更新操作对象
private $bulkWrite;
/**
* Mongo constructor. 初始化
*/
public function __construct(){
$connString = "mongodb://".$this->connectInfo['host'].":".$this->connectInfo['port'];
$this->conn = new \MongoDB\Driver\Manager($connString);
$this->database = $this->connectInfo['database'];
$this->bulkWrite = new \MongoDB\Driver\BulkWrite();
}
/**
* 数据库连接
* @author jinanav 2019年9月3日12:07:15
* @param array $connInfo 连接参数
* @param bool $debug 是否开启调试
* @return $this;
*/
public function connect(array $connectInfo = []){
}
/**
* 更换数据表/集合
* @author jinanav 2020年7月23日14:58:44
* @param string $table 数据表/集合名
* @return $this
*/
public function table($table){
$this->table = $table;
$this->collection = $this->database.'.'.$this->table;
return $this;
}
/**
* 查询符合字段
* @author jinanav 2020年7月25日10:36:38
* @param string|array $field 字段
* @param int $isChoose 1 正选 2 反选
* @return $this
*/
public function field($field,$isChoose = 1){
if(is_array($field)){
foreach ($field as $value){
$this->options['projection'][$field] = $value;
}
}
if(is_string($field)){
if(strpos($field,',') !== false){
foreach (explode($field,',') as $value){
$this->options['projection'][$value] = $isChoose;
}
}else{
$this->options['projection'][$field] = $isChoose;
}
}
return $this;
}
/**
* 排序
* @author jinanav 2020年7月25日11:32:16
* @param string|array $field 字段
* @param int $sort -1 倒叙 1 正序
* @return $this
*/
public function order($field,$sort = 1){
$this->options['sort'][$field] = $sort;
return $this;
}
/**
* 插入数据
* @author jinanav 2020年7月23日14:59:34
* @param array $data 数据表/集合名
* @return bool
*/
public function insert(array $data){
$this->data($data,1,false);
return (bool)$this->conn->executeBulkWrite($this->collection,$this->bulkWrite);
}
/**
* 批量插入
* @author jinanav 2020年7月23日15:06:18
* @param array $data 数据表/集合名
* @return bool
*/
public function insertAll(array $data){
$this->data($data,1,false);
return (bool)$this->conn->executeBulkWrite($this->collection,$this->bulkWrite);
}
/**
* 查询数据
* @author jinanav 2020年7月23日14:58:53
* @param string $table 数据表/集合名
* @return object|array
*/
public function select(){
$this->buildSql();
$cursor = $this->conn->executeQuery($this->collection,$this->whereParam);
$data = [];
foreach($cursor as $doc) {$data[] = (array)$doc;}
return $data;
}
/**
* 查询单条数据
* @author jinanav 2020年7月25日10:21:10
* @param string $table 数据表/集合名
* @return object|array
*/
public function find(){
$result = $this->select();
return isset($result[0]) ? $result[0] : [];
}
/**
* 查询条件
* @author jinanav 2020年7月24日11:40:15
* @param string $condition 条件参数
* @return $this
*/
public function where(array $condition){
$this->whereParamArray = array_merge($this->whereParamArray,$condition);
return $this;
}
/**
* 条件构造
* @author jinanav 2020年7月24日22:31:24
* @return $this
*/
public function buildWhere(){
$this->whereParam = new \MongoDB\Driver\Query($this->whereParamArray,$this->options);
}
/**
* @author jinanav 2020年7月25日12:43:05
* @param $start
* @param null $length
* @return $this
*/
public function limit($limit,$start = null){
$this->options['limit'] = $limit;
if(!empty($start)) $this->options['skip'] = $start;
return $this;
}
/**
* SQL构造
* @author jinanav 2020年7月24日22:24:44
* @param string $condition 条件参数
* @return $this
*/
public function buildSql(){
$error = null;
empty($this->table) && $error = '缺少集合';
if(!empty($error)) return $this->error();
//构造where
$this->buildWhere();
}
/**
* 更新数据
* @author jinanav 2020/7/25 13:19
* @param array $data 需要更新的数据
* @param array $option 更新配置
* //multi为true,代表更新找到的所有记录,false默认更新找到的第一条
* //upsert为true代表如果没有此条记录就执行插入操作,默认false不插入
* @return bool
*/
public function update(array $data,array $option = ["multi" => false, "upsert" => false]){
$this->data($data,2,false,$option);
$writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);
return (bool)$this->conn->executeBulkWrite($this->collection, $this->bulkWrite, $writeConcern);
}
/**
* 删除数据
* @author jinanav 2020年7月25日14:48:12
* @param array|string $data
* @return
*/
public function delete(array $data = []){
$this->data($data,3,false);
$writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);
return (bool)$this->conn->executeBulkWrite($this->collection, $this->bulkWrite, $writeConcern);
}
/**
* 拼装数据
* @author jinanav 2020年7月25日13:21:39
* @param array $data 数据集
* @param int $type 操作类型 1 插入 2 更新 3删除
* @return $this|bool
*/
public function data(array $data = [],$type = 1,$returnThis = true,$option = []){
$this->dataParam = array_merge($this->dataParam,$data);
//先构建好where语句
$this->buildWhere();
if($type == 1) {
//如果是一维数组
if(count($this->dataParam) == count($this->dataParam,1)){
$this->bulkWrite->insert($this->dataParam);
}else{
foreach ($this->dataParam as $value){$this->bulkWrite->insert($value);}
}
}elseif($type == 2){
$this->bulkWrite->update($this->whereParam,['$set'=>$this->dataParam],$option);
}else{
if(empty($this->dataParam)) $this->dataParam['limit'] = 1;
$this->bulkWrite->delete($this->whereParam,$this->dataParam);
}
return $returnThis ? $this : true;
}
}
操作演示
include "Db.php";
include "mongodb/Mongo.php";
use phporm\mongodb\Mongo;
$mongo = new Mongo();
//删除
var_dump($mongo->table('chen')->where(['age'=>18])->delete());
//更新
//var_dump($mongo->table('chen')->where(['age'=>18])->find());
//查询
//var_dump($mongo->table('chen')->order('age',-1)->limit(1)->select());
//插入
//$data = [
// '_id' => 2,
// 'age' => 19,
// 'name' => '郑瘦瘦'
//];
//
//var_dump($mongo->table('chen')->insert($data));
image.png
image.png
因为是初稿,很多高级功能,例如where复杂条件查询,自动载入,内部逻辑优化等等都未来得及实现,后面将会一一实现