Home Backend Development PHP Tutorial 一个非常完美的读写ini格式的PHP配置类分享_php实例

一个非常完美的读写ini格式的PHP配置类分享_php实例

May 16, 2016 pm 08:23 PM
Read and write

基本满足所有配置相关的需求。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

/**

 * 解析.ini格式的配置文件为一个树形结构的对象

 * 配置文件不同section通过冒号继承

 * 默认根据hostname确定使用的section,如果不能确定就优先使用production

 * 检测环境的时候总是优先检测production,其余section按定义顺序检测

 *

 * @author ares@phpdr.net

 *   

 */

class Config {

 /**

 * 解析后的配置文件

 *

 * @var stdClass

 */

 private $config;

 /**

 * 一个二维数组,键是配置文件的section

 * 值是一个数组或回调函数

 * 如果是数组则计算hostname是否在数组中决定是否使用该section

 * 如果是回调函数通过返回值true或false来确定是否使用该section

 *

 * @var array

 */

 private $map = array ();

  

 /**

 * section会被解析,:表示继承

 * 配置项中的'.'用来区分层级关系

 * section中的'.'不会被解析,配置中的数组不受影响。

 *

 * @param string $conf    

 * @throws ErrorException

 * @return stdClass

 */

 function __construct($conf, $map) {

 $config = $this->parseIni ( ( object ) parse_ini_string ( $conf, true ) );

 if (array_key_exists ( 'production', $map )) {

  $production = $map ['production'];

  unset ( $map ['production'] );

  $map = array_merge ( array (

   'production' => $production ), $map );

 } else {

  throw new ErrorException ( 'production section not found in config' );

 }

 $section = 'production';

 $hostname = gethostname ();

 foreach ( $map as $k => $v ) {

  if (is_array ( $v )) {

  foreach ( $v as $v1 ) {

   if ($v1 == $hostname) {

   $section = $k;

   break 2;

   }

  }

  } elseif (is_callable ( $v )) {

  if (true == call_user_func ( $v )) {

   $section = $k;

   break;

  }

  } else {

  throw new ErrorException ( 'Wrong map value in ' . __CLASS__ );

  }

 }

 $this->config = $config->$section;

 }

  

 /**

 * 总是返回配置对象

 *

 * @return mixed

 */

 function __get($key) {

 if (isset ( $this->config->$key )) {

  return $this->config->$key;

 }

 }

  

 /**

 * 切分

 *

 * @param stdClass $v    

 * @param string $k1    

 * @param mixed $v1    

 */

 private function split($v, $k1, $v1) {

 $keys = explode ( '.', $k1 );

 $last = array_pop ( $keys );

 $node = $v;

 foreach ( $keys as $v2 ) {

  if (! isset ( $node->$v2 )) {

  $node->$v2 = new stdClass ();

  }

  $node = $node->$v2;

 }

 $node->$last = $v1;

 if (count ( $keys ) > 0) {

  unset ( $v->$k1 );

 }

 }

  

 /**

 * parseIni

 *

 * @param object $conf    

 * @return stdClass

 */

 private function parseIni($conf) {

 $confObj = new stdClass ();

 foreach ( $conf as $k => $v ) {

  // 是section

  if (is_array ( $v )) {

  $confObj->$k = ( object ) $v;

  foreach ( $v as $k1 => $v1 ) {

   call_user_func ( array (

    $this,

    'split' ), $confObj->$k, $k1, $v1 );

  }

  } else {

  call_user_func ( array (

   $this,

   'split' ), $confObj, $k, $v );

  }

 }

 unset ( $conf );

 // 处理继承

 foreach ( $confObj as $k => $v ) {

  if (false !== strpos ( $k, ':' )) {

  if (0 === strpos ( $k, ':' )) {

   throw new ErrorException ( 'config ' . $k . ' is invalid, ':' can't be the first char' );

  } elseif (1 < substr_count ( $k, ':' )) {

   throw new ErrorException ( 'config ' . $k . ' is invalid, ':' can appear only once' );

  } else {

   $keys = explode ( ':', $k );

   if (! isset ( $confObj->$keys [1] )) {

   throw new ErrorException ( 'parent section ' . $keys [1] . ' doesn't exist in config file' );

   } else {

   if (isset ( $confObj->$keys [0] )) {

    throw new ErrorException ( 'config is invalid, ' . $keys [0] . ' and ' . $k . ' conflicts' );

   } else {

    $confObj->$keys [0] = $this->deepCloneR ( $confObj->$keys [1] );

    $this->objectMergeR ( $confObj->$keys [0], $v );

    unset ( $confObj->$k );

   }

   }

  }

  }

 }

 return $confObj;

 }

  

 /**

 * php默认是浅克隆,函数实现深克隆

 *

 * @param object $obj    

 * @return object $obj

 */

 private function deepCloneR($obj) {

 $objClone = clone $obj;

 foreach ( $objClone as $k => $v ) {

  if (is_object ( $v )) {

  $objClone->$k = $this->deepCloneR ( $v );

  }

 }

 return $objClone;

 }

  

 /**

 * 递归的合并两个对象

 *

 * @param unknown $obj1    

 * @param unknown $obj2    

 */

 private function objectMergeR($obj1, $obj2) {

 foreach ( $obj2 as $k => $v ) {

  if (is_object ( $v ) && isset ( $obj1->$k ) && is_object ( $obj1->$k )) {

  $this->objectMergeR ( $obj1->$k, $v );

  } else {

  $obj1->$k = $v;

  }

 }

 }

}

Copy after login

简单使用:

1

2

3

4

5

6

7

$_ENV ['config'] = new Config ( file_get_contents ( __DIR__ . '/config.ini' ), array (

 'development' => array (

  'localhost.localdomain',

  'localhost'

 ),

 'production' => array ()

) );

Copy after login

配置文件示例:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

[product]

db.default.dsn="mysql:host=127.0.0.1;dbname=default"

db.default.username=root

db.default.password=123456

 

admin.username=admin

admin.password=123456

 

php.error_reporting=E_ALL

php.display_errors=no

php.log_errors=yes

php.error_log=APP_PATH'/resource/log/phpError.log'

php.session.save_path=APP_PATH'/resource/data/session'

 

[development:product]

db.test1.dsn="mysql:host=127.0.0.1;dbname=test1"

db.test1.username=root

db.test1.password=123456

php.display_errors=yes

Copy after login

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use PHP to implement data caching, reading and writing functions How to use PHP to implement data caching, reading and writing functions Sep 05, 2023 pm 05:45 PM

How to use PHP to implement data caching and read-write functions. Caching is an important way to improve system performance. Through caching, frequently used data can be stored in memory to increase the reading speed of data. In PHP, we can use various methods to implement data caching and reading and writing functions. This article will introduce two common methods: using file caching and using memory caching. 1. Use file caching. File caching stores data in files for subsequent reading. The following is a sample code that uses file caching to read and write data:

Practical combat: hard disk io read and write test on Linux Practical combat: hard disk io read and write test on Linux Feb 19, 2024 pm 03:40 PM

Concept fio, also known as FlexibleIOTester, is an application written by JensAxboe. Jens is the maintainer of blockIOsubsystem in LinuxKernel. FIO is a tool used to test network file system and disk performance. It is often used to verify machine models and compare file system performance. It automatically sends fio commands to a list of cluster machines and collects IOPS for small files and throughput data for large files. rw=[mode]rwmixwrite=30 In mixed read and write mode, writing accounts for 30% moderead sequential read write sequential write readwrite sequential mixed read and write randwrite random write r

Revealing the inner workings of Java file operations Revealing the inner workings of Java file operations Feb 28, 2024 am 08:22 AM

File System APIThe internal principles of Java file operations are closely related to the file system API of the operating system. In Java, file operations are provided by the java.nio.file module in the java.NIO package. This module provides an encapsulation of the file system API, allowing Java developers to use a unified API to perform file operations on different operating systems. File Object When a Java program needs to access a file, it first needs to create a java.nio.file.Path object. The Path object represents a path in the file system, which can be an absolute path or a relative path. Once the Path object is created, you can use it to get various properties of the file, such as the name

Decrypt the reading and writing methods of processing DBF files in Java Decrypt the reading and writing methods of processing DBF files in Java Mar 29, 2024 pm 12:39 PM

Decrypting the reading and writing methods of processing DBF files in Java DBF (dBaseFile) is a common database file format that is usually used to store tabular data. In Java programs, processing the reading and writing of DBF files is a relatively common requirement. This article will introduce how to use Java to decrypt this process and provide specific code examples. 1. Reading DBF files In Java, reading DBF files usually requires the use of third-party libraries, such as the dbfread library. First, you need to configure the project

How to deal with concurrent reading and writing data consistency issues in Java development How to deal with concurrent reading and writing data consistency issues in Java development Jun 29, 2023 am 08:10 AM

In Java development, it is very important to deal with the issue of concurrent read and write data consistency. With the popularity of multi-threaded and distributed systems, simultaneous reading and writing of data is becoming more and more common, and if not handled carefully, it may lead to data inconsistency. This article will introduce several common methods to deal with concurrent read and write data consistency issues. 1. Use lock mechanism One of the most commonly used methods to deal with concurrent read and write data consistency issues is to use a lock mechanism (such as the synchronized keyword or the ReentrantLock class). Pass

PHP implements reading and writing operations of Excel files PHP implements reading and writing operations of Excel files Jun 18, 2023 am 10:03 AM

As a commonly used table file format, Excel files are often used in the development process. As a commonly used programming language, PHP also supports reading and writing operations on Excel files. In this article, we will introduce how to use PHP to read and write Excel files. Install the PHPExcel library PHPExcel is an open source PHP library that can easily read and write Excel files. It can be installed through Composer or downloaded directly from GitHub

PHP file reading and writing tutorial: Detailed introduction to the basic methods and processes of reading and writing PHP file reading and writing tutorial: Detailed introduction to the basic methods and processes of reading and writing Sep 06, 2023 pm 12:12 PM

PHP file reading and writing tutorial: Detailed introduction to the basic methods and processes of reading and writing Introduction: When developing web applications, file reading and writing operations are very basic and common operations. PHP provides a series of methods and functions to implement file reading and writing operations, and is very simple and easy to use. This tutorial will introduce in detail the basic methods and processes of reading and writing files in PHP, and give code examples. 1. Reading and opening files Before starting to read files, you first need to open the files. Can be opened through the fopen() function

How to use Golang to achieve fast reading and writing of web applications How to use Golang to achieve fast reading and writing of web applications Jun 24, 2023 pm 03:24 PM

With the popularity of the Internet, Web applications have become an important tool for business marketing and social communication. Fast reading and writing of web applications is a basic issue in web application design. As an efficient and concise programming language, Golang can help programmers achieve their needs for fast reading and writing. In this article, we will learn how to use Golang to achieve fast reading and writing of web applications. 1. Establish a database connection. Before using Golang to implement fast reading and writing of web applications, we need to establish

See all articles