[英]How do I escape a new line character in a .ini file so that Zend_Config_Ini reads it literally?
[英]How does one specify a file path relative to the location of the config file when Zend_Config_Ini is in use?
我想使用该应用程序的Zend_Config
实例内部的configs
参数将一组通用功能嵌入到Zend_Application
实例中。 但是,从属配置文件希望能够引用相对于其自身的路径中的内容。 例如:
$ /应用/ CONFIGS /的application.ini:
[base]
config[] = APPLICATION_PATH "../CasCommon/Configs/common.ini
$ / CasCommon / CONFIGS /使用common.ini
[base]
resources.frontController.controllerDirectory[] = PATH_TO_THIS_IN_DIR "../Controllers"
resources.frontController.actionHelperPaths.Cas_Common_Helper = PATH_TO_THIS_IN_DIR "../ControllerHelpers"
;...
一个人怎么能做到这样的事情?
PHP支持Ini文件中的常量,但不幸的是,它不支持魔术常量,因此您不能使用__DIR__
来解决问题。 最简单,最明显的方法是将application.ini文件的路径定义为常量,就像使用APPLICATION_PATH
,例如
// application.ini
foo = INI_PATH '/../somewhere/else'
// index.php
const INI_PATH = '/path/to/config/folder';
然后,只需定期加载您的Zend_Application
或实例化一个新的Zend_Config
,常量将按照您的需要进行评估。
评论后编辑
我发现关于上述观点的争论不够自然。 在标准ZF项目中,在index.php文件中定义了APPLICATION_PATH
,这也是默认的application.ini加载的位置 。 您所要做的就是在其中添加常量。 Ini文件本身将不存在,因此有人必须在某个时候调用外部库(可能您是开发人员)。 上述解决方案需要一行设置。 任何其他解决方案都需要更多的工作。
如果那对您还不够好,您可以扩展Zend_Application
以在加载application.ini之前自动添加该常量:
class My_Zend_Application extends Zend_Application
{
protected function _loadConfig($file)
{
if (!defined('PATH_TO_INI')) {
define('PATH_TO_INI', dirname(realpath($file)));
}
return parent::_loadConfig($file);
}
}
当然,您仍然必须更改index.php才能使用扩展的My_Zend_Application
,这就是为什么我觉得这种方法毫无意义,因为您还可以只在index.php文件中添加常量。
当然,自定义Zend_Application
将限制您使用application.ini,因为您无法再在运行时更改常量。 因此,如果您需要多个Ini文件(而不仅仅是application.ini)具有此功能,请扩展Zend_Config_Ini
并在返回之前检查相对路径标记的每个值,例如
class My_Config_Ini extends Zend_Config_Ini
{
protected $_relativePath;
protected $_relativePathMarker = '%REL_PATH%';
public function __construct($filename, $section = null, $options = false)
{
$this->_relativePath = dirname(realpath($filename));
parent::__construct($filename, $section, $options);
}
public function get($name, $default = null)
{
if (array_key_exists($name, $this->_data)) {
return $this->_containsRelativePathMarker($this->_data[$name])
? $this->_expandRelativePath($this->_data[$name])
: $this->_data[$name];
}
return $default;
}
protected function _containsRelativePathMarker($value)
{
return strpos($value, $this->_relativePathMarker) !== FALSE;
}
protected function _expandRelativePath($value)
{
return str_replace('%REL_PATH%', $this->_relativePath, $value);
}
}
以上假设您使用类似以下内容编写Ini文件
foo = %REL_PATH% '/../foo.txt'
如果那仍然不是您想要的,我只能再一次鼓励您提出确切的要求。 当您不愿意在这里接受任何答案时,提供500个信誉是没有意义的,因为我们没有读懂您的想法。
另一个选择是(如果您将allowModifications
选项设置为true)是更改工作目录,然后将文件夹更改为realpath。 甚至在加载文件后将路径放在前面。
$config = new Zend_Config_Ini('config.ini', 'section', array(
'allowModifications' => true,
));
$dir = getcwd();
chdir('..');
$config->path = realpath($config->path);
chdir($dir);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.