提取一種對數(shù)據(jù)庫配置的通用方式
目的是通過通用類訪問配置文件的方式,提供對數(shù)據(jù)庫連接的動態(tài)獲取和設(shè)置,使開發(fā)時和生產(chǎn)應(yīng)用時都能夠提供靈活的、簡化的、解耦的操作方式。比如在配置文件中配置好兩套數(shù)據(jù)庫訪問內(nèi)容,一套測試庫訪問地址,一套生產(chǎn)庫訪問,在需要獲取連接信息時,只要填入符合的參數(shù)即可
結(jié)構(gòu)
使用方式
db-config.json,內(nèi)容為數(shù)據(jù)庫連接信息;db-config.php提供公共靜態(tài)訪問,供上層接口調(diào)用;見代碼
{ "debug": { "db_host": "", "db_name": "", "db_user": "", "db_password": "" }}php類
<?phpclass DbConf{ public static function Conf( $conf_name ){ if(empty($conf_name)){ die("Illegal parameter"); } $from = "localhost"; // allow legal host only if(!isset($_SERVER['HTTP_HOST']) || $_SERVER['HTTP_HOST']!=$from){ die("Unauthorized access"); } $json_config = file_get_contents('db-config.json'); $json_data = json_decode($json_config, true); if( array_key_exists($conf_name, $json_data)){ return $json_data[$conf_name]; }else{ return "Not Found"; } }}這篇文章就介紹到這了,需要的朋友可以參考一下
新聞熱點
疑難解答
圖片精選