The purpose is to provide a dynamic access and setting of database connections by accessing the configuration file by Universal class, so as to provide flexible, simplified and decoupled operation mode for both development and production applications.
Extracting a common way to configure a database
The goal is to provide dynamic access and provisioning of database connections through a generic class that accesses configuration files, enabling flexible, simplified, and decoupled operations in both development and production applications. For example, in the configuration file configuration two sets of database access content, a set of test library access address, a set of production library access, when you need to obtain the connection information, just fill in the parameters to match
Structure
Factory mode, pass the parameter, return the result;
The array is returned successfully, otherwise a string error message is returned;
Two files work together, one is a JSON format configuration file, is responsible for saving the database connection content, the other is to read the class, responsible for reading and retrieving, return the results;
How to use
Define the configuration file as db-config.json
, the content is the database connection information;
The Read class db-config.php
provides public static access for the upper interface to invoke;
The upper interface uses the interface method $db _conf = dbconf::conf ("Debug"); Retrieves the database connection information for the debug flag. If there is $db _conf array format;
See Code
{"Debug": { "db_host": "", "db_name": "", "Db_user": "", "Db_password": ""}}
PHP class
<?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";}} }
This article is introduced to this, the need for friends can refer to
Articles you may be interested in:
PHP connection to MySQL database and output in JSON format related explanations
PHP automatically recognizes the current use of mobile terminal de related explanations
Phpstorm method for local breakpoint debugging