简体   繁体   中英

Best practice for storing settings for a website?

Originally, my intention is to create a class (Object oriented) to store settings as constant. For example, in PHP:

class Settings{
     const test = 'foobar!';
}

But later on, I think that this approach does not let the Admin user modify these settings. It seems that only non-necessary-to-modify settings should be declared as constant, and others should be declared as private variable, then the application will find whether settings are available in the database Setting table first, if not, it will use default from get(), set() function defined in Settings class. Is that a good approach? What is the best approach? I appreciate any pieces advice on this issue.

I a prefer similar to your method, but using a private static property key=>value array with a getter and setter. That way later you can tie them to a file or db.

$value = Classname::getparam('configsetting');
Classname::setparam('configsetting', $newvalue);

Dont forget to make the get/set param mehods public static!

Here's the full class would look something like...

class Classname{
    private static  $params = null;  

    public static function getparam($key){
        if(is_null(self::$params){
             self::$params = array();
             //initialize param array here from file, db, or just hardcoded values...
        }
        return isset(self::$params[$key])?self::$params[$key]:null;
     }

    public static function setparam($key, $value){
        if(is_null(self::$params){
             self::$params = array();
             //initialize array here
        }
        self::$params[$key] = $value;
     }
 } 

Straight answer :: Your method is fine, its all preference.

Depending on if the settings are going to be changed you may want to look into mysql storage or storing settings to a file, but if they aren't going to be changed your method is fine if thats what your comfortable with.

您可能希望考虑使用YAML等格式的配置文件。

I usually keep the settings values that are not necessary to modify as constant and other settings that has the modify option into the database(getter/setter). Then I cache the data for a longer period of time so that I dont have to access database for each request. When admin changes any settings, cache is invalidated and new value is stored in cache.

There is an another approach of storing settings data in XML files. Can anybody tell me what is the advantage of storing settings data in XML file compared to storing it in database?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM