• 打造一套属于自己的php开发框架(一)封装Db类


    一直使用thinkphp或者laravel框架,越到后面越发现,这些框架占用太大了,最主要的是很多东西完全用不到,我就想为啥不能自己封装一个?想到就搞,这个是一个Db类,主要封装了MySQL的增删改查方法,使用起来类似thinkphp和laravel。

    多的不说了,直接上代码:

    
    
    class Db
    {
        protected static \PDO $connection; // 数据库连接
        protected static string $table; // 数据表名
        protected static array $wheres = []; // 查询条件
        protected static ?int $findId = null; // 查找的记录 ID
        protected static bool $initialized = false; // 数据库连接是否已初始化
    
        // 确保数据库连接已建立
        protected static function ensureConnection()
        {
            if (!self::$initialized) {
                self::$connection = new \PDO("mysql:host=localhost;dbname=数据库名称", "数据库用户名", "数据库密码");
                self::$initialized = true;
            }
        }
    
        // 设置数据表名
        public static function table(string $table): self
        {
            self::ensureConnection();
            self::$table = $table;
            return new self();
        }
    
        // 设置查询条件
        public static function where(string $column, string $operator, $value): self
        {
            self::$wheres[] = compact('column', 'operator', 'value');
            return new self();
        }
    
        // 根据 ID 查询记录
        public static function find(int $id): array
        {
            self::ensureConnection();
            $query = "SELECT * FROM " . self::$table . " WHERE id = :id";
            $statement = self::$connection->prepare($query);
            $statement->execute([':id' => $id]);
            return $statement->fetch(\PDO::FETCH_ASSOC);
        }
    
        // 查询符合条件的记录
        public static function get(): array
        {
            self::ensureConnection();
            $query = "SELECT * FROM " . self::$table;
    
            if (!empty(self::$wheres)) {
                $query .= " WHERE ";
                foreach (self::$wheres as $where) {
                    $query .= "{$where['column']} {$where['operator']} '{$where['value']}' AND ";
                }
                $query = rtrim($query, " AND ");
            }
    
            $statement = self::$connection->prepare($query);
            $statement->execute();
            return $statement->fetchAll(\PDO::FETCH_ASSOC);
        }
    
        // 分页查询
        public static function paginate(int $page = 1, int $perPage = 10): array
        {
            self::ensureConnection();
            $offset = ($page - 1) * $perPage;
            $query = "SELECT COUNT(*) as count FROM " . self::$table;
    
            if (!empty(self::$wheres)) {
                $query .= " WHERE ";
                foreach (self::$wheres as $where) {
                    $query .= "{$where['column']} {$where['operator']} '{$where['value']}' AND ";
                }
                $query = rtrim($query, " AND ");
            }
    
            $statement = self::$connection->prepare($query);
            $statement->execute();
            $totalResults = $statement->fetchColumn();
    
            $query = "SELECT * FROM " . self::$table;
            if (!empty(self::$wheres)) {
                $query .= " WHERE ";
                foreach (self::$wheres as $where) {
                    $query .= "{$where['column']} {$where['operator']} '{$where['value']}' AND ";
                }
                $query = rtrim($query, " AND ");
            }
            $query .= " LIMIT $perPage OFFSET $offset";
    
            $statement = self::$connection->prepare($query);
            $statement->execute();
            $results = $statement->fetchAll(\PDO::FETCH_ASSOC);
    
            $totalPages = ceil($totalResults / $perPage);
    
            return [
                'data' => $results,
                'total' => $totalResults,
                'perPage' => $perPage,
                'currentPage' => $page,
                'totalPages' => $totalPages,
            ];
        }
    
        // 插入数据
        public static function insert(array $data): bool
        {
            self::ensureConnection();
            $columns = implode(', ', array_keys($data));
            $placeholders = implode(', ', array_fill(0, count($data), '?'));
            $values = array_values($data);
    
            $query = "INSERT INTO " . self::$table . " ($columns) VALUES ($placeholders)";
            $statement = self::$connection->prepare($query);
            return $statement->execute($values);
        }
    
        // 更新数据
        public static function update(array $data, int $id): bool
        {
            self::ensureConnection();
            $updates = [];
            foreach ($data as $column => $value) {
                $updates[] = "$column = ?";
            }
            $setClause = implode(', ', $updates);
    
            $query = "UPDATE " . self::$table . " SET $setClause WHERE id = ?";
            $values = array_values($data);
            $values[] = $id;
    
            $statement = self::$connection->prepare($query);
            return $statement->execute($values);
        }
    
        // 删除数据
        public static function delete(int $id): bool
        {
            self::ensureConnection();
            $query = "DELETE FROM " . self::$table . " WHERE id = ?";
            $statement = self::$connection->prepare($query);
            return $statement->execute([$id]);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148

    使用方法:

    假设有一个名为 users数据表

    1.插入一条数据

    Db::table('users')->insert(['name' => 'John', 'age' => 30]);
    
    • 1

    2.查询 ID 为 1 的记录

    $result = Db::table('users')->find(1);
    var_dump($result); // 输出查询结果
    
    • 1
    • 2

    3.更新 ID 为 1 的记录

    Db::table('users')->update(['age' => 35], 1);
    
    • 1

    4.查询年龄大于 30 的用户,并分页显示

    $users = Db::table('users')->where('age', '>', 30)->paginate(1, 10);
    var_dump($users); // 输出分页结果
    
    • 1
    • 2

    5.删除 ID 为 1 的记录

    Db::table('users')->delete(1);
    
    • 1

    大概就是这样了,实现了简单的增删改查,如果不够的可以自己添加一些代码

  • 相关阅读:
    使用水泥路肩培土两用机进行施工一次制作成型
    【华为机试真题 JAVA】求解连续数列-100
    【附源码】Python计算机毕业设计图书销售网站
    概率公式c的计算
    拉索回归(Lasso)算法原理讲解
    云服务器下搭建 NFS 网络文件系统
    字符串定义
    深度学习 Day 20——优化器对比实验
    T1 小美的数组询问(15分) - 美团编程题 & 题解
    pat basic 1050 螺旋矩阵
  • 原文地址:https://blog.csdn.net/qq_36901092/article/details/137893491