I need to have some configuration options on my website.
I thought it would be easiest to maintain if different options are placed in different files.
Also I need to have a class to retrieve the options from different configuration files.
In the directory structure of my website I created a directory called /setup
In this directory I have several files for the different configuration options, eg: /setup/base.php
The contents of base.php will look something like the following:
$setup = new stdClass();
$setup->currencies = array('USD', 'EUR', );
$setup->locations = array('local', 'international', );
I would like to create a class which reads the file and returns the different options.
class Options
{
function __construct($option)
{
if (!is_file(SETUP_DIR.'/'.$option.'.php')) {
thrown new Exception('Configuration file not found.');
}
$options = // get information from file
return $options; // this should return the currencies and locations
}
}
$options = new Options('base');
However I don’t know whether this is the correct way of doing it.
If so I cannot think of a way to retrieve the options from the setup files in the class.
Can you help me with this or at least point me in the right direction?
Well, I don’t think there is a right way for this one: Zend uses .ini files, Codeigniter has a set of arrays, and Symfony uses YAML. WordPress stores most everything in the database, and has one config file which it just includes.
Personally, I’m partial to ini files — ini is something which is used all over the place, so it has a feeling of, “I can reuse this if necessary”, but I think that the only “wrong” solution here is one which is inconsistent — if you’re using ini, use ini, if arrays, arrays, but don’t mix.
In your case, there are a couple of options. These two seem to be among the most common. (both of these examples assumes that the stdClass object is named
$optionsin the loaded file) You could create a wrapper:Or, you could use a Singleton pattern and just return the objects in the individual classes:
Or, you could combine them: