0

Currently, I store some settings in a database table. It contains 2 fields (setting_name, setting_value).

Now, all my models need access to these settings (for example, there is a setting which decides how many records a query should return at max), but I'm not sure how to implement it with good OO practices. Is there an accepted/good way of doing this (so all models have access to the config settings)?

Also, should I cache these settings (retrieving them is actually just 1 query per pageload) as some people seem to recommend this?

Thanks

TheBoyan
  • 6,802
  • 3
  • 45
  • 61
Bv202
  • 3,924
  • 13
  • 46
  • 80

2 Answers2

2

I handle this through my Dependency Injection Container a.k.a. Service Container. When the container is initialised, I simply execure the query and create an associative array (well, ArrayObject really) out of all the config settings. Then I register this array as a service in my Service Container. That way, my entire application can easily access the configuration like so:

$config = $this->container->get('configuration');
do_something($config['bar']);
Sander Marechal
  • 22,978
  • 13
  • 65
  • 96
  • According to another thread, such service container is also bad: http://stackoverflow.com/questions/6034748/if-singletons-are-bad-why-a-service-container-is-good what is your opinion on this? I'm getting confused with all options and deciding which ones are good/bad :s – Bv202 Jul 14 '11 at 13:26
  • @Bv202: You're reading the other question wrong. Many Dependency Injection Containers double up as Service Containers. A SC without DI is just as bad as a Singleton (opinions vary on how bad they are). A SC that is a DIC is not evil, because it exposes it's dependencies instead of hiding them. – Sander Marechal Jul 14 '11 at 13:31
1

The solution to this problem is the Singleton pattern.

You should have a single instance class with static methods to get configuration values:

Config::getConfigData($conf_key)

Caching: it depends on how many configuration data you have in your db. I suggest to cache those and not to perform a query every time you need a value.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Fabrizio D'Ammassa
  • 4,729
  • 25
  • 32
  • I've been thiking of a Singleton already, but as soon as you start talking about it, you get a lot of negative response and opinions on why a Singleton is bad. Is it a good thing to use in this situation? – Bv202 Jul 14 '11 at 13:23
  • See http://www.geekpad.ca/blog/post/simple-php-config-file-using-singleton and http://www.ibm.com/developerworks/library/os-php-config/index.html for more details. – Fabrizio D'Ammassa Jul 14 '11 at 13:31