初始化仓库及v1.0.0提交
This commit is contained in:
0
app/Config/.gitkeep
Normal file
0
app/Config/.gitkeep
Normal file
57
app/Config/AppConfig.php
Normal file
57
app/Config/AppConfig.php
Normal file
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Config;
|
||||
|
||||
class AppConfig
|
||||
{
|
||||
private static ?array $cache = null;
|
||||
private static string $configPath = '';
|
||||
|
||||
private static function getConfigPath(): string
|
||||
{
|
||||
if (self::$configPath === '') {
|
||||
self::$configPath = dirname(__DIR__, 2) . '/config/app-config.json';
|
||||
}
|
||||
|
||||
return self::$configPath;
|
||||
}
|
||||
|
||||
private static function load(): array
|
||||
{
|
||||
if (self::$cache !== null) {
|
||||
return self::$cache;
|
||||
}
|
||||
|
||||
$path = self::getConfigPath();
|
||||
|
||||
if (!file_exists($path)) {
|
||||
self::$cache = [];
|
||||
return self::$cache;
|
||||
}
|
||||
|
||||
$content = file_get_contents($path);
|
||||
self::$cache = json_decode($content, true) ?? [];
|
||||
|
||||
return self::$cache;
|
||||
}
|
||||
|
||||
public static function get(string $key, $default = null)
|
||||
{
|
||||
$config = self::load();
|
||||
return $config[$key] ?? $default;
|
||||
}
|
||||
|
||||
public static function set(string $key, $value): void
|
||||
{
|
||||
$config = self::load();
|
||||
$config[$key] = $value;
|
||||
self::$cache = $config;
|
||||
|
||||
$dir = dirname(self::getConfigPath());
|
||||
if (!is_dir($dir)) {
|
||||
mkdir($dir, 0755, true);
|
||||
}
|
||||
|
||||
file_put_contents(self::getConfigPath(), json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
|
||||
}
|
||||
}
|
||||
39
app/Config/Database.php
Normal file
39
app/Config/Database.php
Normal file
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace App\Config;
|
||||
|
||||
use PDO;
|
||||
use PDOException;
|
||||
|
||||
class Database
|
||||
{
|
||||
private static ?PDO $instance = null;
|
||||
|
||||
private function __construct()
|
||||
{
|
||||
$configPath = dirname(__DIR__, 2) . '/config/db-config.json';
|
||||
|
||||
if (!file_exists($configPath)) {
|
||||
throw new PDOException('数据库配置文件不存在');
|
||||
}
|
||||
|
||||
$config = json_decode(file_get_contents($configPath), true);
|
||||
|
||||
$dsn = "mysql:host={$config['host']};port={$config['port']};dbname={$config['dbname']};charset=utf8mb4";
|
||||
|
||||
self::$instance = new PDO($dsn, $config['user'], $config['password'], [
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
||||
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
||||
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4",
|
||||
]);
|
||||
}
|
||||
|
||||
public static function getInstance(): PDO
|
||||
{
|
||||
if (self::$instance === null) {
|
||||
new self();
|
||||
}
|
||||
|
||||
return self::$instance;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user