2008年11月5日星期三

[fw-core] Zend_Config_Ini with variable expansion

I have liked other platforms were in the ini file you can do something like

[globla]
rootDir=/tmp
configDir=${rootDir}/etc

and have the ${variable} expanded.

so my solution was to extend Zend_Config_Ini to support this.
I also added the ability to pass an array to Zend_Config_Ini just like ot
can to Zend_Config so the application can pass initial parameters that may
be needed in the ini file to be used to expand variables.

<?php
class My_Config_Ini extends Zend_Config_Ini
{

public function __construct($filename, $section = null, $options =
false, array $array = array())
{
parent::__construct($filename, $section, $options);
$this->merge(new Zend_Config($array));
$this->_postProcessValues($this);
}

protected function _postProcessValues($config)
{
foreach ($config as $key => $value) {
if (is_a($value, "Zend_Config")) {
$this->_postProcessValues($value);
} else {
$config->__set($key, preg_replace_callback("|\\\${(.*)}|",
array($this, 'callback'), $value));
}
}
}

public function callback($matches)
{
if (isset($matches[1])) {
$path = explode($this->_nestSeparator, $matches[1]);

$result = $this;
foreach($path as $value) {
if(!isset($result->$value)) {
return $matches[0];
}
$result = $result->$value;
}
return $result;
}
return $matches[0];
}
}


This is how I use it:

$config = new My_Config_Ini(self::normalizePath($this->configDir .
'/config.ini'), $configSection, true, array('rootDir' => $this->rootDir,
'configDir' => $this->configDir, 'configDir' => $this->configDir));


then in my ini file i can do stuff like


[global]
a = 1
b = 2

c.a = 1
c.b = 1

d.a = ${a}/foo
d.b = ${c.a}/bar

Should this be something I submit to the proposals or it's not interseting
enough?

--
View this message in context: http://www.nabble.com/Zend_Config_Ini-with-variable-expansion-tp20343188p20343188.html
Sent from the Zend Core mailing list archive at Nabble.com.

没有评论: