PHP Access Database Configuration General Method of json

  • 2021-10-13 06:44:08
  • OfStack

Extract a common way to configure a database

The purpose is to provide dynamic access and setting of database connection by accessing configuration files through general classes, so that flexible, simplified and decoupled operation modes can be provided in development and production applications. For example, configure two sets of database access contents, one set of test library access address and one set of production library access in the configuration file. When you need to obtain connection information, you only need to fill in the corresponding parameters

Structure

Factory mode, pass parameters and return results; array is returned successfully, otherwise string error message is returned; Two files work together, one is json format configuration file, which is responsible for saving database connection content, and the other is reading class, which is responsible for reading and retrieving and returning results;

Usage

Define the profile as db-config.json The content is database connection information; Read class db-config.php Provide public static access for upper interface call; The upper interface uses the interface method $db_conf = DbConf:: Conf ("debug"); Retrieves database connection information marked by debug. If there is $db_conf in array format;

See code


{
 "debug": {
  "db_host": "",
  "db_name": "",
  "db_user": "",
  "db_password": ""
 }
}

Class php


<?php
class 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 here, and friends who need it can refer to 1


Related articles: