PHP类,用于处理INI文件

用于处理INI文件的Helper类。该类实现了Builder设计模式。在提出的课程中,提供了用于处理INI文件的功能的实现。基本功能包括创建,添加和读取部分,添加和删除键以及其他功能。


首先,您需要声明负责文件结构,文件路径和扫描类型的变量:

/**
 * @var array  ini 
*/
private array $structure = [];
/**
 * @var int  
*/
private int $scannerMode;
/**
 * @var string   
*/
private string $path;

在方法的构造函数中,指定文件的路径(用于创建)和扫描的类型,还调用该方法以获取文件结构:

public function __construct(string $path, int $scannerMode = INI_SCANNER_TYPED) {
	$this->path = $path;
	file_put_contents($path, null, LOCK_EX);
	$this->scannerMode = $scannerMode;

	$this->setInitStructure();
}

:

private function setInitStructure(): void {
	$this->structure = parse_ini_file($this->path, true, $this->scannerMode);
}

parse_ini_file , . true, . :

  • INI_SCANNER_NORMAL ( PHP)

  • INI_SCANNER_RAW

INI_SCANNER_RAW ( => ) . PHP 5.6.1 INI_SCANNER_TYPED. boolean, null integer , , .  "true""on"  "yes"   TRUE"false""off""no"  "none"  FALSE"null"   NULL. , , , . , , .

:

public function getStructure(): array {
	return $this->structure;
}

- . :

public function getSection(string $section): array {
	return $this->structure[$section];
}

public function getValue(string $section, string $key) {
	return $this->getSection($section)[$key];
}

, , . , . :

public function addSection(string $section): Ini {
	if (array_key_exists($section, $this->structure)) {
		throw new Exception(" {$section}  ");
	}

	$this->structure[$section] = [];

	return $this;
}

exception, .

, :

public function addValues(string $section, array $values): Ini {
	$this->structure[$section] = array_merge($values, $this->structure[$section]);

	return $this;
}

, . :

public function setValues(string $section, array $values): Ini {
  foreach ($values as $key => $value) {
  	$this->structure[$section][$key] = $value;
  }

  return $this;
}

, , :

public function removeSection(string $section): Ini {
  unset($this->structure[$section]);

  return $this;
}

public function removeKeys(string $section, array $keys): Ini {
  foreach ($keys as $key) {
  	unset($this->structure[$section][$key]);
  }

  return $this;
}

, "".

- :

public function write(): void {
  $iniContent = null;

  foreach ($this->structure as $section => $data) {
  	$iniContent .= "[{$section}]\n";

  foreach ($data as $key => $value) {
  	$iniContent .= "{$key}={$value}\n";
  }

  $iniContent .= "\n";
  }

	file_put_contents($this->path, $iniContent, LOCK_EX);
  $this->setInitStructure();
}

我希望这个PHP INI文件助手对您有所帮助。如果有改进的建议,我将很高兴听到他们的建议。




All Articles