TP5 封装 mongoDB
先在thinkphp下面的helper.php文件中定义如下代码:
//助手函数 mongoDB
if (!function_exists('mongoDB')) {
/**
* 获取容器对象实例
* @return Container
*/
function mongo($table) {
\module\mongoDB::$table = $table;
return \module\mongoDB::mongo();
}
}
然后再extend文件夹下创建module/mongoDB.php:代码:
<?php
/**
* Created by PhpStorm.
* User: Mac
* Date: 2018/8/20
* Time: 下午1:52
*/
namespace module;
use think\Db;
class mongoDB {
public static $table;
public static function mongo() {
return Db::connect(Config('Mongo_db'))->table(\module\mongoDB::$table);
}
}
在配置文件config.php中定义:
// +----------------------------------------------------------------------
// | mysql设置 配合Mongodb
// +----------------------------------------------------------------------
'Mongo_db' => [
// 数据库类型
'type' => '\think\mongo\Connection',
// 服务器地址
'hostname' => '数据库地址',
// 数据库名
'database' => 'chat',
// 用户名
'username' => '',
// 密码
'password' => '',
// 端口
'hostport' => '27017',
// 连接dsn
'dsn' => '',
// 数据库连接参数
'params' => [],
// 数据库编码默认采用utf8
'charset' => 'utf8',
// 数据库表前缀
'prefix' => '',
//转换主键
'pk_convert_id' => true,
],
调用时是这样的:
mongo('chat')->insert([
'from' => is_string($fromid) ? $fromid : strval($fromid),
'from_name' => model('server')->get_username($fromid),
'toid' => is_string($toid) ? $toid : strval($toid),
'to_name' => model('server')->get_username($toid),
'msg' => (new mongoAES())->encrypt($name_img),
'msg_type' => '2', //1:文本; 2:图片
'access_type' => '1',//1:wed 接入; 2:微信
'from_type' => '2', //1:游客; 2:客服
'addtime' => time(),
'tag_name' => getTagName($fromid,$toid)
]);