TP5 封装 mongoDB

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); 
    } 
} 

调用时是这样的:

 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) 
            ]); 

猜你喜欢

转载自blog.csdn.net/weixin_44251321/article/details/88419723
tp5