What is the best way to represent configuration options internally?

oop, php

Solution

Of those 3 options, a static method is probably the best.

Really, though, "the best" is ultimately about what's easiest and most consistent for you to use. If the rest of your app isn't using any OO code then you might as well go with option #1. If you are ultimately wanting to write a whole db abstraction layer, option #2.

Without knowing something more about what your goals are and what the rest of your app looks like, it's kind of like asking someone what the best motor vehicle is -- it's a different answer depending on whether you're looking for a sports car, a cargo truck, or a motorcycle.

Problem

So, I am looking at a number of ways to store my configuration data. I believe I've narrowed it down to 3 ways: Just a simple variable ``` $config = array( "database" => array( "host" => "localhost", "user" => "root", "pass" => "", "database" => "test" ) ); echo $config['database']['host']; ``` I think that this is just too mutable, where as the configuration options shouldn't be able to be changed. A Modified Standard Class ``` class stdDataClass { // Holds the Data in a Private Array, so it cannot be changed afterwards. private $data = array(); public function __construct($data) { // ...... $this->data = $data; // ..... } // Returns the Requested Key public function __get($key) { return $this->data[$key]; } // Throws an Error as you cannot change the data. public function __set($key, $value) { throw new Exception("Tried to Set Static Variable"); } } $config = new stdStaticClass($config_options); echo $config->database['host']; ``` Basically, all it does is encapsulates the above array into an object, and makes sure that the object can not be changed. Or a Static Class ``` class AppConfig{ public static function getDatabaseInfo() { return array( "host" => "localhost", "user" => "root", "pass" => "", "database" => "test" ); } // .. etc ... } $config = AppConfig::getDatabaseInfo(); echo $config['host']; ``` This provides the ultimate immutability, but it also means that I would have to go in and manually edit the class whenever I wanted to change the data. Which of the above do you think would be best to store configuration options in? Or is there a better way?

Original source

Related problems