Best solution for “Array chaining”

viewsonic

New Member
For my project I wrote a small config class that loads its data from a .ini file. It overwrites the magic __get() method in order to provide simplified access to the (read only) config values. Example config.ini.php:\[code\];<?php exit; ?>[General]auth = 1user = "halfdan"[Database]host = "127.0.0.1"\[/code\]My config class (singleton pattern - simplified here) looks like this:\[code\]class Config { protected $config = array(); protected function __construct($file) { // Preserve sections $this->config = parse_ini_file($file, TRUE); } public function __get($name) { return $this->config[$name]; }}\[/code\]Loading the config would create an array structure like this:\[code\]array( "General" => array( "auth" => 1, "user" => "halfdan" ), "Database" => array( "host" => "127.0.0.1" ))\[/code\]It's possible to access the first level of the array by doing \[code\]Config::getInstance()->General\[/code\], and the values using \[code\]Config::getInstance()->General['user']\[/code\]. What I really want though is being able to access all configuration variables by doing \[code\]Config::getInstance()->General->user\[/code\] (syntactic sugar). The array is not an object and the "->" isn't defined on it, so this simply fails.I thought of a solution and would like to get some public opinion about it:\[code\]class Config { [..] public function __get($name) { if(is_array($this->config[$name])) { return new ConfigArray($this->config[$name]); } else { return $this->config[$name]; } }}class ConfigArray { protected $config; public function __construct($array) { $this->config = $array; } public function __get($name) { if(is_array($this->config[$name])) { return new ConfigArray($this->config[$name]); } else { return $this->config[$name]; } }}\[/code\]This would allow me to chain my configuration access. As I'm using PHP 5.3 it might also be a good idea to let ConfigArray extend ArrayObject (SPL is activated per default in 5.3).Any suggestions, improvements, comments?
 
Back
Top