如何使用Zend_Config_Writer_ini保留application.ini路径


How to preserve application.ini paths using Zend_Config_Writer_Ini

我目前正在Phing中开发一个构建系统,该系统采用Zend Framework项目模板,并根据Phing参数进行配置。我遇到的一个问题是在使用Zend_Config_Writer_Ini时。

我的Phing任务从repo中获取一个名为application.default.ini的预填充文件,并使用Zend_Config_ini修改该文件以添加构建文件中的参数(数据库详细信息等(。然后,它将其写入application.ini,以便项目使用。相关任务代码的简化版本如下所示:

$appConfig = new Zend_Config_Ini(
    $appDefaultConfigPath, 
    null, 
    array(
        'skipExtends' => true,
        'allowModifications' => true
    )
);
$appConfig->production->resources->db->params->host = $buildProperties->db->host;
$appConfig->production->resources->db->params->username = $buildProperties->db->username;
$appConfig->production->resources->db->params->password = $buildProperties->db->password;
$appConfig->production->resources->db->params->dbname = $buildProperties->db->dbname;
$writer = new Zend_Config_Writer_Ini();
$writer->setConfig($appConfig)
       ->setFilename($appConfigPath)
       ->write();

就数据库凭据而言,这很好,但当涉及到包含已定义常量的预填充路径时,就会出现问题。例如:

bootstrap.path = APPLICATION_PATH "/Bootstrap.php"

变为:

bootstrap.path = "APPLICATION_PATH/Bootstrap.php"

在读取/写入不同的ini文件时,有没有任何方法可以保留这些配置行,或者我应该在运行任务之前重组构建文件以复制文件,只修改需要更改的ini行?

当您加载现有配置时,所有常量都已被转换,即,如果您使用print_r查看对象,您将无法再找到您的常量。因此,使用编写器打印完整路径,而不是常量。

在您的情况下,我猜常量在您的环境中不存在,因此按原样打印。

更新:更具体地说。Zend_Config_Ini::_parseIniFile()使用parse_ini_file()读取ini文件,该文件将常量作为实际路径加载。请参阅php.net文档示例#2

直接来自php.net注释:

如果ini文件中的常量与用单引号引起来的字符串,它们只能用双引号以使常数展开。

示例:

define('APP_PATH','/some/PATH'(;

mypath=APP_PATH'/config'//不会扩展常量:[mypath]=>APP_PATH"/config">

mypath=APP_PATH"/config"//将扩展常量:[mypath]=>/some/path/config

所以你可以用单引号重写你的路径。。。bootstrap.path = APPLICATION_PATH '/Bootstrap.php'

然后用双引号替换CCD_ 4的所有出现(一个简单的Regex应该这样做(。

作为替代方案,您可以使用Phing的Filter来替换配置模板中的令牌。

任务示例:

<target name="setup-config" description="setup configuration">
    <copy file="application/configs/application.ini.dist" tofile="application/configs/application.ini" overwrite="true">
        <filterchain>
            <replacetokens begintoken="##" endtoken="##">
                <token key="DB_HOSTNAME" value="${db.host}"/>
                <token key="DB_USERNAME" value="${db.user}"/>
                <token key="DB_PASSWORD" value="${db.pass}"/>
                <token key="DB_DATABASE" value="${db.name}"/>
            </replacetokens>
        </filterchain>
    </copy>
</target>

此任务将application/configs/application.ini.dist复制到application/configs/application.ini,并用phing属性${db.host} 的值替换像##DB_HOSTNAME##这样的令牌

我想要使用Zend_Config的便利性,同时保留使用APPLICATION_PATH常量的能力,所以在Zend_Config_Writer保存文件后,我最终用一个简单的正则表达式修复了该文件。

$writer->write();
// Zend_Config_Writer messes up the settings that contain APPLICATION_PATH
$content = file_get_contents($filename);
file_put_contents($filename, preg_replace('/"APPLICATION_PATH(.*)/', 'APPLICATION_PATH "$1', $content));