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

简介: 风.fox thinkphp5.x之Collection(集合)解析 php集合 http://blog.csdn.net/fenglailea/article/details/52723586 thinkphp5 数据库 链接 http://blog.csdn.net/fenglailea/article/details/52728899 db函数本函数没什么

风.fox
thinkphp5.x之Collection(集合)解析 php集合
http://blog.csdn.net/fenglailea/article/details/52723586
thinkphp5 数据库 链接
http://blog.csdn.net/fenglailea/article/details/52728899

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&param2=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);
    }
}
目录
相关文章
|
22天前
|
存储 C++ 容器
C++入门指南:string类文档详细解析(非常经典,建议收藏)
C++入门指南:string类文档详细解析(非常经典,建议收藏)
31 0
|
23天前
|
XML 存储 Java
Spring重要类解析
Spring重要类解析
20 0
|
24天前
|
API 数据库 C语言
【C/C++ 数据库 sqlite3】SQLite C语言API返回值深入解析
【C/C++ 数据库 sqlite3】SQLite C语言API返回值深入解析
164 0
|
25天前
|
消息中间件 存储 数据库
RocketMQ 流数据库解析:如何实现一体化流处理?
RocketMQ 5.0 是一款云原生的消息中间件,旨在覆盖更多业务场景。它针对国内企业在数字化转型中面临的多场景消息处理需求,提供了一体化的解决方案。
111897 7
|
8天前
|
存储 中间件 关系型数据库
数据库切片大对决:ShardingSphere与Mycat技术解析
数据库切片大对决:ShardingSphere与Mycat技术解析
14 0
|
7天前
|
Java
Java 15 神秘登场:隐藏类解析未知领域
Java 15 神秘登场:隐藏类解析未知领域
11 0
|
24天前
|
存储 程序员 编译器
【C++ 模板类与虚函数】解析C++中的多态与泛型
【C++ 模板类与虚函数】解析C++中的多态与泛型
46 0
|
25天前
|
Python
Python类与对象:深入解析与应用
本文介绍了Python中的核心概念——类和对象,以及它们在面向对象编程中的应用。类是用户定义的类型,描述具有相同属性和行为的对象集合;对象是类的实例,具备类的属性和方法。文章通过示例讲解了如何定义类、创建及使用对象,包括`__init__`方法、属性访问和方法调用。此外,还阐述了类的继承,允许子类继承父类的属性和方法并进行扩展。掌握这些概念有助于提升Python编程的效率和灵活性。
|
29天前
|
存储 Shell Linux
【Shell 命令集合 文件管理】Linux 更新locate命令所使用的数据库 updatedb命令解析
【Shell 命令集合 文件管理】Linux 更新locate命令所使用的数据库 updatedb命令解析
153 0
|
29天前
|
存储 安全 程序员
【C++ 包装器类 智能指针】完全教程:std::unique_ptr、std::shared_ptr、std::weak_ptr的用法解析与优化 — 初学者至进阶指南
【C++ 包装器类 智能指针】完全教程:std::unique_ptr、std::shared_ptr、std::weak_ptr的用法解析与优化 — 初学者至进阶指南
66 0

推荐镜像

更多