Fastest way to store easily editable config data in PHP?

后端 未结 7 1355
借酒劲吻你
借酒劲吻你 2020-12-01 03:46

What is the fastest way to store config data in PHP so that it is easily changeable (via PHP)? First I thought about having config.php file, but I can\'t edit it on fly with

相关标签:
7条回答
  • 2020-12-01 04:17

    Whilst it's most likely overkill for what you're after, but what I tend to do is store the config data in a database using a PHP class to control the changes to the name/value pairs within. (i.e.: There's no direct DB access from outside this class.)

    When a call is made to the PHP config class to change a value, this then writes out a standard PHP include file with all of various values defined on it.

    As such, there's no load time performance hit when reading the config data and all config data can be changed within the database via a CMS module.

    0 讨论(0)
  • 2020-12-01 04:24

    I am pretty sure you are correct about the int/string values and yes JSON is a way but serialize and unserializing a string will be faster for speed optimization:

    This link will help you:

    http://docs.php.net/serialize

    0 讨论(0)
  • 2020-12-01 04:26

    The way I store configuration is to put some variables in an external .php file and then when I want to use those files, I say:

    <?php include("fileName"); ?>

    And that would allow you to share configuration information across many pages. I am not, however, sure that this is the most efficient method, but it seemed to be the easiest to me.

    0 讨论(0)
  • 2020-12-01 04:30

    Serialize is a better option than JSON for storing PHP variables.

    I like to use var_export for saving config file, and using include for loading config info. This makes it easy to save config data progmatically AND makes the data easy to read/write for a person as well:

    config.php:

    return array(
     'var1'=> 'value1',
     'var2'=> 'value2',
    );
    

    test.php:

    $config = include 'config.php';
    $config['var2']= 'value3';
    file_put_contents('config.php', '<?php return ' . var_export($config, true) . ';');
    

    Updated config.php now contains the following:

    return array(
     'var1'=> 'value1',
     'var2'=> 'value3',
    );
    
    0 讨论(0)
  • 2020-12-01 04:35

    You should use serialize as opposed to json_encode:

    http://docs.php.net/serialize

    0 讨论(0)
  • 2020-12-01 04:36

    I use a database with a table called config or settings. The table has two columns:

    name [varchar(255)]
    value [varchar(255)]
    

    This allows the easy storage of int's, float's, and short strings.

    Then I create two functions, GetSetting and SetSetting. These store a row and retrieve a row, respectively. I find that this simplifies the storing of values tremendously.

    0 讨论(0)
提交回复
热议问题