Reputation: 48933
On my site I have a config file which has many settings that need to be accessed in many pages, including inside many class files. The config file is included into the header of every page build. Since I will be using a registry method to store some objects in, I am wondering if it would be better for me to store some setting in this class ass well since it will be available to all my other objects? From my experience over the last couple days, it seems accessing CONSTANTS inside of my class files is difficult sometimes. I am just not sure if it would be a good idea as it would need to call several methods to set and get the settings. Is it common practice to store settings in a registry type object? I have seen on some large projects that they have the methods in place to set/get settings but I have never really seen it in action.
Upvotes: 0
Views: 163
Reputation: 19247
I avoid constants in PHP, they make untestable. This is the gist of my preferred solution:
whatever.ini:
<?php
return array(
'setting-1' => 'value',
'setting-2' => 'another value',
);
config.php:
class config
{
public function __construct($path)
{
$this->cfg = include $path;
}
private $cfg;
public function get($key, $default)
{
return array_key_exists($this->cfg, $key)
? $this->cfg[$key]
: $default
;
}
}
index.php:
$cfg = new config('my.ini');
...
Upvotes: 2
Reputation: 655
I use a combination of two approaches:
1: In every class/controller, I always start with a require_once('app_config.php') in which I have code like:
define('APP_SMTP_SERVER', 'mail.company.com');
that I can then reference as a constant.
2: I have a singleton "Registry" class where I can store keys and values. It has two exposed methods, getAttribute($key) and setAttribute($key, $value). When I save it to the database, I serialize the value, so it can store any data type you throw at it (single values or arrays, etc.).
Upvotes: 1
Reputation: 60413
I like to keep things like this in a registry of some sort. Although for me this is because
With that said i think it really depends on what the values are and how you intend to use them and if they are structure or essentially flat.
Upvotes: 1