使用Zend_Config_Writer添加注释或格式


Add comments or formatting with Zend_Config_Writer

我一直在玩Zend_Config_Writer,虽然我可以让它做我想做的事,但我发现缺乏格式有点令人不安,因为:

[production : general]
;
; Production site configuration data.
;
locale                                          = sv_SE
...

成为

[production : general]   
locale                                          = sv_SE
...

我意识到"新"配置是基于Zend_Config对象中保存的值编写的,并且此对象不包含任何注释或平淡的行,但这使得新配置很难阅读,特别是对于我的同事。

这能以某种方式解决吗?我想出的最好的方法是使用具有"级联"继承的不同部分,但这似乎是一个愚蠢的想法

正如你所说,Zend_Config_Writer不会呈现任何注释,因为它们不存储在Zend_Config对象中。根据您要渲染的ini文件的结构,您可以使用"级联",至少可以清除冗余(对我来说它看起来并不那么愚蠢,即使在标准的application.ini配置文件中也是如此......

当然,另一种解决方案可能是使用或创建其他东西来编写您的 ini 文件,但这可能有点矫枉过正。

希望有帮助,

经过一些实验,我通过以下方式解决了我的问题并成功测试了它。

  1. 将配置拆分为多个文件。就我而言,我有 1 个大型应用程序.ini它几乎包含我所有的配置和 1 个小版本.ini其中包含一些特定于版本的数据
  2. 单独创建所有(在我的例子中为 2)Zend_Config_ini对象,但在一个对象上设置 allowModification
  3. 使用 Zend_Config_Ini->Merge() 功能合并所有配置,然后将其设置为只读
  4. 要更新配置的任何部分,请从该特定 ini 文件创建一个新的Zend_Config_ini对象,并将其设置为允许修改和跳过范围
  5. 更新配置并使用Zend_Config_Writer_ini写入更改

示例代码:

/* Load the config */    
//Get the application-config and set 'allowModifications' => true
$config = new Zend_Config_Ini('../application/configs/application.ini',$state, array('allowModifications' => true));
//Get the second config-file
$configVersion = new Zend_Config_Ini('../application/configs/version.ini');
//Merge both config-files and then set it to read-only
$config->merge($configVersion);
$config->setReadOnly();
/* Update a part of the config */
$configVersion = new Zend_Config_Ini(
        APPLICATION_PATH.'/configs/version.ini',
        null,
        array('skipExtends' => true, 'allowModifications' => true)
    );
//Change some data here
$configVersion->newData = "Some data";
//Write the updated ini
$writer = new Zend_Config_Writer_Ini(
        array('config' => $configVersion, 'filename' => 'Path_To_Config_files/version.ini')
    );
    try
    {
        $writer->write();
    }
    catch (Exception $e) {
        //Error handling
    }