💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
## 创建core/Database.php ``` <?php namespace core; use core\database\connection\MysqlConnection; class Database { protected $connections = []; // all connection // 获取默认链接 protected function getDefaultConnection() { return \App::getContainer()->get('config')->get('database.default'); } // 设置默认链接 public function setDefaultConnection($name) { \App::getContainer()->get('config')->set('database.default', $name); } // 根据配置信息的name来创建链接 public function connection($name = null) { if (isset($this->connections[$name])) // 如果存在就直接返回 return $this->connections[$name]; if ($name == null) // 选择默认链接 $name = $this->getDefaultConnection(); $config = \App::getContainer()->get('config')->get('database.connections.' . $name); // 获取链接的配置 $connectionClass = null; // 链接处理的类 switch ($config['driver']) { case 'mysql': $connectionClass = MysqlConnection::class; break; // 如果有其他类型的数据库 那就继续完善 } $dsn = sprintf('%s:host=%s;dbname=%s', $config['driver'], $config['host'], $config['dbname']); try { $pdo = new \PDO($dsn, $config['username'], $config['password'], $config['options']); } catch (\PDOException $e) { die($e->getMessage()); } return $this->connections[$name] = new $connectionClass($pdo, $config); } // 代理模式 public function __call($method, $parameters) { return $this->connection()->$method(...$parameters); } } ``` ## 创建core/database/connection/Connection.php ``` <?php namespace core\database\connection; // 链接的基础类 class Connection { protected $pdo; protected $tablePrefix; protected $config; public function __construct($pdo, $config) { $this->pdo = $pdo; $this->tablePrefix = $config['prefix']; $this->config = $config; } } ``` ## 创建core/database/connection/MysqlConnection.php ``` <?php namespace core\database\connection; // 继承基础类 class MysqlConnection extends Connection { protected static $connection; public function getConnection() { return self::$connection; } // 执行sql public function select($sql, $bindings = [], $useReadPdo = true) { $statement = $this->pdo; $sth = $statement->prepare($sql); try { $sth->execute( $bindings); return $sth->fetchAll(); } catch (\PDOException $exception){ echo ($exception->getMessage()); } } } ``` ## 绑定db ![](https://img.kancloud.cn/3a/e9/3ae9e95fd3e26ed1c89419a80c5e15e8_727x322.png) ## 运行 ![](https://img.kancloud.cn/71/24/712426b4f6c86382a9bd02ee715bf8cb_727x240.png) ![](https://img.kancloud.cn/0c/93/0c933a58d25a79f8ee85c3ef1d3d3089_877x413.png) ### 关于数据库配置 config/database.php ``` <?php return [ 'default' => 'mysql_one', 'connections' => [ 'mysql_one' => [ 'driver' => 'mysql', 'host' => '134.175.80.215', // 这是我的一个远程服务器 没用的 但是也别乱搞 'username' => 'php_frame', 'dbname' => 'php_frame', 'password' => '12345678', 'prefix' => '', 'options' => [ ] ], ] ]; ```