You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123 lines
3.1 KiB

<?php
/**
* 配置管理类
*/
class Config {
private static $instance = null;
private $config = [];
/**
* 单例模式获取实例
*/
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/**
* 构造函数,加载配置文件
*/
private function __construct() {
$configPath = __DIR__ . '/../config/config.php';
if (file_exists($configPath)) {
$this->config = include $configPath;
} else {
$this->config = $this->getDefaultConfig();
}
}
/**
* 获取默认配置
*/
private function getDefaultConfig() {
return [
'smtp' => [
'port' => 25,
'host' => '0.0.0.0',
'max_connections' => 100,
],
'pop3' => [
'port' => 110,
'host' => '0.0.0.0',
'max_connections' => 100,
],
'server' => [
'domain' => 'test.com',
'admin_password' => 'admin123',
'max_email_size' => 10 * 1024 * 1024,
],
'log' => [
'path' => '../logs/',
'level' => 'info',
'max_file_size' => 10 * 1024 * 1024,
],
'mailbox' => [
'max_size' => 100 * 1024 * 1024,
],
];
}
/**
* 获取配置值
* @param string $key 配置键,支持点号分隔,如 'smtp.port'
* @param mixed $default 默认值
* @return mixed 配置值
*/
public function get($key, $default = null) {
$keys = explode('.', $key);
$value = $this->config;
foreach ($keys as $k) {
if (isset($value[$k])) {
$value = $value[$k];
} else {
return $default;
}
}
return $value;
}
/**
* 设置配置值
* @param string $key 配置键
* @param mixed $value 配置值
*/
public function set($key, $value) {
$keys = explode('.', $key);
$config = &$this->config;
foreach ($keys as $i => $k) {
if ($i === count($keys) - 1) {
$config[$k] = $value;
} else {
if (!isset($config[$k]) || !is_array($config[$k])) {
$config[$k] = [];
}
$config = &$config[$k];
}
}
}
/**
* 保存配置到文件
* @return bool 是否保存成功
*/
public function save() {
$configPath = __DIR__ . '/../config/config.php';
$content = "<?php\n/**\n * 邮件服务器配置文件\n */\n\nreturn " . var_export($this->config, true) . ";\n";
return file_put_contents($configPath, $content) !== false;
}
/**
* 获取所有配置
* @return array 所有配置
*/
public function getAll() {
return $this->config;
}
}