Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$settings array or Config Class to store project settings?

How should I store settings for project?

Which is better - to use a $settings array with all my settings:

$settings['max_photos'] = 30;
//...

or create a singleton Config class with all the settings in it?

Class Config {
    private $max_photos = 30;
    //...
}

Any good examples?

like image 394
ideea Avatar asked Jul 17 '10 07:07

ideea


4 Answers

I think it is best to use constants for configuration. For example using class constants:

class Config {
    const
    max_photos     = 30,
    something_else = 100,
    // ...
    ;
}

echo Config::max_photos;

If you have PHP 5.3 you could also define them as global constants:

const MAX_PHOTOS = 30;

echo MAX_PHOTOS;

But I think this is far less clean and straightforward.

Obviously this will only work as long as you are only storing constants, i.e. scalar, non-expression values. If your configuration contains arrays for example, this won't work anymore. In this case I would use a Config class with public static properties:

class Config {
    public static $per_page = 30;
    public static $array = array(...);
}

echo Config::$per_page;

The latter is very similar to the $config array approach, but has the benefit (or may this be a drawback?) that the class is accessible from everywhere including functions and classes, whereas the array is accessible only in the global space unless you import it into functions/classes using global $config;.

like image 72
NikiC Avatar answered Oct 21 '22 12:10

NikiC


Either will work nicely, do whichever you feel most comfortable with.

like image 29
Toby Allen Avatar answered Oct 21 '22 12:10

Toby Allen


The best way is to store your setting in a file . and to manipulate this file declare a class which does operations on file

like image 41
Sagar Varpe Avatar answered Oct 21 '22 12:10

Sagar Varpe


If you go for the array approach, you could use array literals for slightly more readable code:

$settings = array(
    'max_photos' => 30,
    'max_width'  => 100
    //...
)
like image 32
Eric Avatar answered Oct 21 '22 10:10

Eric