1、实现效果
config(include_once $coreConfig); //加载配置文件
config() //获取所有配置
config('DB_HOST') 获取配置
2、按层级配置文件加载,存取配置项 config,function.php
function config($var=NULL,$value=NULL){
static $config=array();
if(is_array($var)){
//加载配置文件config.php
$config=array_merge($config,array_change_key_case($var,CASE_UPPER));
return ;
}
if(is_string($var)){
//取值
$var=strtoupper($var);
if(!is_null($value)){
$config[$var]=$value;
return ;
}
return isset($config[$var])?$config[$var]:NULL;
}
if(is_null($var)&&is_null($value)){
//获取所有配置
return $config;
}
}
3、引入三个配置config.php文件 KJ.php
//加载文件
private static function _import_file(){
$fileArr=array(
FILE_PATH.'/function.php',
COMMON_PATH.'/function.php',
MODULE_PATH.'/function.php',
);
foreach ($fileArr as $v){
if(is_file($v)){
require_once $v;
}
}
$coreConfig= FILE_PATH.'/config.php';
$commonConfig= COMMON_PATH.'/config.php';
$moduleConfig=MODULE_PATH.'/config.php';
//加载配置文件 优先配置最外层配置
if(is_file($coreConfig)) config(include_once $coreConfig);
if(is_file($commonConfig)) config(include_once $commonConfig);
if(is_file($moduleConfig)) config( include_once $moduleConfig);
}
4、设置file及common下面config.php配置
<?php
return [
'DB_HOST'=>'localhost',//数据库地址
'DB_DATABASE'=>'aaa',//数据库
'DB_USER'=>'root',//数据库账号
'DB_PWD'=>'root',//数据库密码
];
5、数据库配置修改,取值ModelBase.php
private function _connect(){
if($this->pdo){
return true;
}
$host = config('DB_HOST');
$db = config('DB_DATABASE');
$user = config('DB_USER');
$pass =config('DB_PWD');
$dsn = "mysql:host=$host;dbname=$db;charset=utf8";
try {
$this->pdo = new PDO($dsn, $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
} catch (PDOException $e) {
die("数据库连接失败: " . $e->getMessage());
}
}