tp5 封装助手函数之mongo()

1, 先在创建拓展文件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); 
    } 
} 

2, 修改助手函数文件thinkphp/helper.php,增加如下代码:

//助手函数 mongo
if (!function_exists('mongoDB')) {
    /**
     * 获取容器对象实例
     * @return Container
     */
    function mongo($table) {
        \module\mongoDB::$table = $table;
        return \module\mongoDB::mongo();
    }
}

3, 修改配置文件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,
    ],

4, 使用示例:

$data = [ 
    'username' => is_string($username) ? $username: strval($username), 
    'age' => 12, 
    'job' => 'doctor', 
];
 mongo('user')->insert($data); 

最后附上原文链接:https://blog.csdn.net/weixin_44251321/article/details/88419723 

猜你喜欢

转载自blog.csdn.net/weixin_43652106/article/details/88600093
今日推荐