I am working on a personal framework and I have been trying to move all of my configuration variables into one central file and read them from there.
I created a config class that traverses a large array, but I feel as I add more configurations to the application, its performance won't be sufficient. I am wondering if there is a better way to accomplish this.
class config {
private static $config = null;
private static $delimiter = '->';
private static function &load( $path ) {
if ( is_null( self::$config ) ) {
self::$config = include(dirname(__FILE__).'/'.CONFIG_DIR);
}
if ( !is_array( $path ) ) {
$path = explode( self::$delimiter,$path );
}
$array =& self::$config;
$i = 0;
while( $i < count( $path ) ) {
if ( $i !== ( count( $path ) - 1 ) ) {
$array =& $array[$path[$i]];
}
elseif ( $i == ( count( $path ) - 1 ) ) {
return $array[$path[$i]];
}
$i++;
}
}
private static function removeNull( $data ) {
if ( is_array( $data ) ) {
$array = array();
foreach( $data as $key => $val ) {
if ( is_array( $val ) ) {
$array[$key] = self::removeNull( $val );
}
elseif ( !is_null( $val ) ) {
$array[$key] = $val;
}
}
return $array;
}
elseif ( !is_null( $data ) ) {
return $data;
}
}
public static function get( $path ) {
return self::removeNull( self::load( $path ) );
}
public static function set( $path,$data ) {
$value =& self::load( $path );
$value = $data;
}
public static function remove( $path ) {
self::set( $path,null );
}
}
There are a few parts of the code that won't make sense, so don't comment on those. Pretty much the class loads a file containing an array and traverses it, getting/setting/removing vars using a path.
ex.
$user = config::get('database->username');
//or
$templ = config::get('templates->member->edit');
Also, I hope there is a better way of removing elements from the array, instead of setting them to null. I had to do this because using unset doesn't work on a referenced variable.
Hope someone can understand my problem. If you need some testable code, I will be happy to rewrite the code to work on your server and provide a config array to test with.