PHP 專案常見設定格式:PHP 陣列、XML、YAML、INI。Zend Framework 採用 INI。PHP 5.3+ 可透過 dba 擴充搭配 inifile handler 高效讀寫 INI,並實作 SPL 介面實現原生陣列式存取。
DbaReader (實作 Iterator)<?php
class DbaReader implements Iterator {
protected $db = NULL;
private $key = false;
private $val = false;
public function __construct($file, $handler) {
if (!$this->db = dba_open($file, 'r', $handler)) {
throw new Exception('Could not open file ' . $file);
}
}
public function __destruct() { dba_close($this->db); }
public function rewind() {
$this->key = dba_firstkey($this->db);
$this->fetch_data();
}
public function next() {
$this->key = dba_nextkey($this->db);
$this->fetch_data();
}
private function fetch_data() {
if ($this->key !== false) $this->val = dba_fetch($this->key, $this->db);
}
public function current() { return $this->val; }
public function valid() { return $this->db && $this->key !== false; }
public function key() { return $this->key; }
}
?>
DbaArray (繼承 DbaReader + 實作 ArrayAccess)<?php
class DbaArray extends DbaReader implements ArrayAccess {
public function __construct($file, $handler) {
$this->db = dba_popen($file, "c", $handler); // "c" = 讀寫建立
if (!$this->db) throw new Exception("Database could not be opened");
}
public function __destruct() { parent::__destruct(); }
public function offsetGet($name) {
$data = dba_fetch($name, $this->db);
if ($data) {
if (ini_get('magic_quotes_runtime')) $data = stripslashes($data);
return $data; // 或 unserialize($data)
}
return NULL;
}
public function offsetSet($name, $value) {
dba_replace($name, $value, $this->db); // 或 serialize($value)
return $value;
}
public function offsetExists($name) { return dba_exists($name, $this->db); }
public function offsetUnset($name) { return dba_delete($name, $this->db); }
}
?>
test.ini:
host = localhost
password = password
database = data
index.php:
<?php
function loadClass($class) { require_once __DIR__ . DIRECTORY_SEPARATOR . $class . '.php'; }
spl_autoload_register('loadClass', false);
$iniFile = __DIR__ . DIRECTORY_SEPARATOR . 'test.ini';
$ini = new DbaArray($iniFile, 'inifile'); // handler: inifile
echo $ini['database']; // data
var_dump($ini); // 可 foreach、isset、unset 操作
?>
inifile (PHP 5.3+)、flatfile、cdb、db4 等。| 方案 | 讀取效能 | 寫入支援 | 適用場景 |
|---|---|---|---|
parse_ini_file() | 極快 (單次解析) | 否 | 純讀取、部署階段產生快取 |
DbaArray | 快 (索引查詢) | 是 | 需執行期動態修改 INI |
Zend_Config_Ini | 中 (物件導向) | 否 | ZF 專案、區段繼承、複雜結構 |
編碼提醒: INI 檔編碼需與 PHP 腳本一致 (UTF-8 推薦),否則中文會亂碼。