当前位置: 移动技术网 > IT编程>开发语言>PHP > thinkphp5.x之数据库操作相关解析 Db类

thinkphp5.x之数据库操作相关解析 Db类

2018年09月13日  | 移动技术网IT编程  | 我要评论

db函数

本函数没什么好说,直接pass

/**
     * 实例化数据库类
     * @param string        $name 操作的数据表名称(不含前缀)
     * @param array|string  $config 数据库配置参数
     * @param bool          $force 是否强制重新连接
     * @return \think\db\query
     */
    function db($name = '', $config = [], $force = true)
    {
        return db::connect($config, $force)->name($name);
    }

db类

// 命名空间
namespace think;
// 框架入口
use think\app;
// 数据集
use think\collection;
// 数据库操作动作类
use think\db\query;
// 分页数据集 处理类
use think\paginator\collection as paginatorcollection;

/**
 * 这里就看出你的开发工具是否强大了。其他地方调用该类,都会有类的方法提示
 * class db
 * @package think
 * @method query table(string $table) static 指定数据表(含前缀)
 * @method query name(string $name) static 指定数据表(不含前缀)
 * @method query where(mixed $field, string $op = null, mixed $condition = null) static 查询条件
 * @method query join(mixed $join, mixed $condition = null, string $type = 'inner') static join查询
 * @method query union(mixed $union, boolean $all = false) static union查询
 * @method query limit(mixed $offset, integer $length = null) static 查询limit
 * @method query order(mixed $field, string $order = null) static 查询order
 * @method query cache(mixed $key = true , integer $expire = null) static 设置查询缓存
 * @method mixed value(string $field) static 获取某个字段的值
 * @method array column(string $field, string $key = '') static 获取某个列的值
 * @method query view(mixed $join, mixed $field = null, mixed $on = null, string $type = 'inner') static 视图查询
 * @method mixed find(mixed $data = []) static 查询单个记录
 * @method mixed select(mixed $data = []) static 查询多个记录
 * @method integer insert(array $data, boolean $replace = false, boolean $getlastinsid = false, string $sequence = null) static 插入一条记录
 * @method integer insertgetid(array $data, boolean $replace = false, string $sequence = null) static 插入一条记录并返回自增id
 * @method integer insertall(array $dataset) static 插入多条记录
 * @method integer update(array $data) static 更新记录
 * @method integer delete(mixed $data = []) static 删除记录
 * @method boolean chunk(integer $count, callable $callback, string $column = null) static 分块获取数据
 * @method mixed query(string $sql, array $bind = [], boolean $fetch = false, boolean $master = false, mixed $class = false) static sql查询
 * @method integer execute(string $sql, array $bind = [], boolean $fetch = false, boolean $getlastinsid = false, string $sequence = null) static sql执行
 * @method paginatorcollection paginate(integer $listrows = 15, mixed $simple = false, array $config = []) static 分页查询
 * @method mixed transaction(callable $callback) static 执行数据库事务
 * @method boolean batchquery(array $sqlarray) static 批处理执行sql语句
 */
class db
{
    //  数据库连接实例
    private static $instance = [];
    // 查询次数
    public static $querytimes = 0;
    // 执行次数
    public static $executetimes = 0;

    /**
     * 数据库初始化 并取得数据库类实例
     * @static
     * @access public
     * @param mixed         $config 连接配置
     * @param bool|string   $name 连接标识 true 强制重新连接
     * @return \think\db\connection
     * @throws exception
     */
    public static function connect($config = [], $name = false)
    {
        // 变量$name值为布尔类型中的假值时,才会执行
        if (false === $name) {
            // 根据配置信息,序列化后,使用md5 生成一个唯一标识
            $name = md5(serialize($config));
        }
        // 变量$name值为布尔类型中的真值时,且
        // 数组 $instance中 $name 的值 不存在时 才会执行
        if (true === $name || !isset(self::$instance[$name])) {
            // 解析连接参数 支持数组和字符串
            $options = self::parseconfig($config);
            // 数据驱动类型不存在,则报错
            if (empty($options['type'])) {
                throw new \invalidargumentexception('underfined db type');
            }
            // 获得 数据库驱动命名空间的地址
            $class = false !== strpos($options['type'], '\\') ? $options['type'] : '\\think\\db\\connector\\' . ucwords($options['type']);
            // 记录初始化信息
            if (app::$debug) {
                log::record('[ db ] init ' . $options['type'], 'info');
            }
            // $name 连接标识 为 true 强制重新连接
            if (true === $name) {
                // 重新实例化 数据库驱动,直接返回该对象
                return new $class($options);
            } else {
                // 重新实例化 数据库驱动,并保存到静态变量$instance[$name]中
                // 我不会告诉你这个是 设计模式中的 单例模式的
                self::$instance[$name] = new $class($options);
            }
        }
        return self::$instance[$name];
    }

    /**
     * 数据库连接参数解析
     * @static
     * @access private
     * @param mixed $config
     * @return array
     */
    private static function parseconfig($config)
    {
        // 数据库参数不存在时
        if (empty($config)) {
            // 读取 默认数据库信息
            $config = config::get('database');
        }
        // 数据库参数$config 是字符串时,且 变量中不含有 / 时 ,执行
        elseif (is_string($config) && false === strpos($config, '/')) {
            // 支持读取配置参数
            $config = config::get($config);
        }
        // 如果是字符串
        if (is_string($config)) {
            // 字符串 解析
            return self::parsedsn($config);
        } else {
            return $config;
        }
    }

    /**
     * dsn解析
     * 格式: mysql://username:passwd@localhost:3306/dbname?param1=val1¶m2=val2#utf8
     * @static
     * @access private
     * @param string $dsnstr
     * @return array
     */
    private static function parsedsn($dsnstr)
    {
        // 解析 ,不知道的同学,请自觉查文档
        $info = parse_url($dsnstr);
        if (!$info) {
            return [];
        }
        // 变量初始化
        $dsn = [
            'type'     => $info['scheme'],
            'username' => isset($info['user']) ? $info['user'] : '',
            'password' => isset($info['pass']) ? $info['pass'] : '',
            'hostname' => isset($info['host']) ? $info['host'] : '',
            'hostport' => isset($info['port']) ? $info['port'] : '',
            'database' => !empty($info['path']) ? ltrim($info['path'], '/') : '',
            'charset'  => isset($info['fragment']) ? $info['fragment'] : 'utf8',
        ];

        if (isset($info['query'])) {
            //解析 ,不知道的同学,请自觉查文档
            parse_str($info['query'], $dsn['params']);
        } else {
            $dsn['params'] = [];
        }
        return $dsn;
    }

    // 调用驱动类的方法
    // __callstatic() 这个方法用来监视一个对象中的静态方法。如果你试着调用一个对象中不存在的静态方法,它将会被自动调用。
    // 不知道的同学,请自觉查文档
    public static function __callstatic($method, $params)
    {
        // 自动初始化数据库
        // call_user_func_array 调用回调函数,并把一个数组参数作为回调函数的参数
        // 不知道的同学,请自觉查文档
        return call_user_func_array([self::connect(), $method], $params);
    }
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网