Zend_Config_Ini 採用熟悉的 INI 格式,支援點號分隔的巢狀鍵值與區段繼承,是中小型專案最常用的設定管理方式。本文詳細說明語法規則、載入選項與實際應用範例。
[production] webhost = www.example.com database.adapter = pdo_mysql database.params.host = db.example.com database.params.username = dbuser database.params.password = secret database.params.dbname = dbname [staging : production] database.params.host = dev.example.com database.params.username = devuser database.params.password = devsecret
[] 內。: 表示繼承,[staging : production] 代表 staging 繼承 production 所有設定,並可覆寫個別鍵值。. 表示巢狀層級,對應物件屬性存取 $config->database->params->host。<?php
$config = new Zend_Config_Ini('/path/to/config.ini', 'staging');
echo $config->database->params->host; // 輸出 "dev.example.com"
echo $config->database->params->dbname; // 輸出 "dbname" (繼承自 production)
?>
<?php
$options = [
'allowModifications' => true, // 允許執行期修改設定值(預設 false)
'nestSeparator' => ':' // 自訂巢狀分隔字元(預設 .)
];
$config = new Zend_Config_Ini('/path/to/config.ini', 'staging', $options);
?>
| 參數 | 說明 |
|---|---|
$filename | INI 檔案路徑 |
$section | 要載入的區段名稱;null 載入所有區段;陣列可載入多區段並合併 |
$options | 選項陣列:allowModifications、nestSeparator |
true/false/yes/no/null 會被 PHP 自動轉型為布林或 null,字串 "true" 需加引號 "true"。{}、|、&)需加雙引號包裹。; 開頭,不可出現在行尾(需獨立一行)。<?php
// 同時載入 production 與 staging,staging 覆寫 production
$config = new Zend_Config_Ini('/path/to/config.ini', ['production', 'staging']);
// 等同於先載入 production,再載入 staging 並合併
?>
allowModifications = false 確保設定不可竄改。Zend_Registry 於 Bootstrap 註冊,全域存取:Zend_Registry::set('config', $config)。