Someone asked if their singleton is good for OOP:
Using a singleton class to get and set program wide settings.
However, the answer just provides tweaks to his existing code - but the question wasn't entirely answered. What is the best practice to use for configuration files so that it doesn't become spaghetti code?
All apps need configuration settings so that it saves time and it looks neat.
I currently use something similar to what was proposed but not a singleton. However, I have a long array that feeds into different constructors. I feel that this is improper or maybe it is.
namespace App;
class Config
{
protected static $config = array();
public static function get($name, $default = null)
{
return isset(self::$config[$name]) ? self::$config[$name] : $default;
}
public static function add($parameters = array())
{
self::$config = array_merge(self::$config, $parameters);
}
}
App\Config::add(
array(
'database' => array(
'default' => array(
'driver' => 'mysql',
'host' => '127.0.0.1',
'username' => 'user',
'password' => '',
'database' => 'database',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci'
),
'tracking' => array(
'driver' => 'mysql',
'host' => '192.168.0.1',
'username' => 'tracking',
'password' => '123456',
'database' => 'tracking',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci'
),
'data' => array(
'driver' => 'mysql',
'host' => '192.168.0.11',
'username' => 'data',
'password' => 'abcder',
'database' => 'data_info',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci'
)
),
'pheanstalk' => array(
'default' => array(
'host' => 'localhost',
'port' => 11400,
'queue_name' => 'queue'
)
),
'app_worker' => array(
'log_files_path' => ROOT.'/logs',
'file_size_limit' => 542880, //5MB
'file_name_extension' => 'w_log',
),
'memcache' => array(
'default' => array(
array(
'host' => 'localhost',
'port' => '11211'
),
array(
'host' => 'localhost',
'port' => '11211'
),
array(
'host' => 'localhost',
'port' => '11211'
)
)
)
)
);
Then in my main program:
$db_config = App\Config::get('database');
Now it's ok for me to add extra configuration needs for different object I might create and etc and I can load up a controller or piece of code to fetch it from. However, I feel that this configuration file that adds all these settings will be terribly long in the long wrong.
I would like to know if there something better, and what. I tried to use inheritance or DI but my configuration file is still long.