PHP's own framework implements config configuration level access (Improvement Part 2)

1. Realize the effect

config(include_once $coreConfig); //Load configuration file
config() //Get all configurations
config('DB_HOST') Get configuration

 

2. Load the hierarchical configuration file and access the configuration items 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. Introduce three configuration config.php files 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. Set the config.php configuration under file and common

<?php
return [
    'DB_HOST'=>'localhost',//数据库地址
    'DB_DATABASE'=>'aaa',//数据库
    'DB_USER'=>'root',//数据库账号
    'DB_PWD'=>'root',//数据库密码
];

5. Database configuration modification, value 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());
        }
    }

Guess you like

Origin blog.csdn.net/weixin_39934453/article/details/132351827