
本文介绍如何通过静态方法从一个配置类(functions)中获取数据库参数,并在另一个连接类(connection)中动态组装 pdo dsn,实现配置与逻辑分离,提升代码可维护性与安全性。
本文介绍如何通过静态方法从一个配置类(functions)中获取数据库参数,并在另一个连接类(connection)中动态组装 pdo dsn,实现配置与逻辑分离,提升代码可维护性与安全性。
在实际 PHP 开发中,将数据库连接参数硬编码在类属性中(如 private $server = "mysql:host=XXX;...")会严重降低灵活性和安全性——一旦配置变更,需修改源码;若配置文件存在敏感信息,也难以统一管控。理想的方案是:将配置集中管理于外部文件(如 INI),并通过静态工具类按需读取,再在连接类中动态构建 DSN。
以下是推荐的重构实践:
✅ 正确做法:延迟初始化 + 配置驱动
将连接参数的获取推迟到 openConnection() 执行时,避免在类定义阶段就依赖未加载的配置:
<?php
class Connection {
protected $con;
private $server;
private $user;
private $pass;
private $options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
public function openConnection() {
try {
// 动态读取配置(确保 Functions 类已引入)
$host = Functions::Get_Config('DB', 'host');
$port = Functions::Get_Config('DB', 'port');
$dbname = Functions::Get_Config('DB', 'name'); // 注意:原问题中 config key 是 'db_name',但示例代码用了 'name',请按实际 INI 键名调整
$user = Functions::Get_Config('DB', 'username');
$pass = Functions::Get_Config('DB', 'password');
// 安全拼接 DSN(port 为空时应省略,避免语法错误)
$dsn = "mysql:host={$host}";
if (!empty($port)) {
$dsn .= ";port={$port}";
}
$dsn .= ";dbname={$dbname}";
$this->con = new PDO($dsn, $user, $pass, $this->options);
return $this->con;
} catch (PDOException $e) {
error_log("PDO Connection failed: " . $e->getMessage());
return null;
}
}
public function closeConnection() {
$this->con = null;
}
}⚠️ 关键注意事项
-
类加载顺序:务必在
class_PDO.php中require_once或include_onceclass_Functions.php,否则Functions::Get_Config()将报错; -
INI 键名一致性:检查
config/config.ini中[DB]段落的键名是否与Get_Config()调用完全匹配(如'db_name'vs'name'),大小写敏感; -
错误防御:
parse_ini_file()可能返回false(文件不存在/权限不足),建议在Get_Config()中增加健壮性判断:public static function Get_Config($section, $key) { $config_file = 'config/config.ini'; if (!file_exists($config_file) || !is_readable($config_file)) { throw new RuntimeException("Config file not found or unreadable: {$config_file}"); } $config_data = parse_ini_file($config_file, true, INI_SCANNER_RAW); if ($config_data === false) { throw new RuntimeException("Failed to parse INI file: {$config_file}"); } if (!isset($config_data[$section][$key])) { throw new InvalidArgumentException("Missing config: [{$section}][{$key}]"); } return $config_data[$section][$key]; } -
密码安全:切勿将密码写入版本库;使用
.gitignore排除config.ini,生产环境通过环境变量或密钥管理服务注入。
✅ 总结
通过将配置读取逻辑移至运行时、解耦静态属性与动态值,并辅以异常处理与校验,不仅能解决跨类变量传递问题,更践行了“关注点分离”原则。这种模式可轻松扩展至多环境(dev/staging/prod)、多数据库实例等场景,是构建可维护 PHP 应用的基础实践。
立即学习“PHP免费学习笔记(深入)”;



















