问题
First of all, I am assuming this is NOT bad practice due to various popular software using this method, such as SMF.
Anyway, so I currently have this code:
<?php
// main visual config
$cfg['lang'] = 'en';
// paths
$path['admin'] = 'index.php?p=admin';
$path['admin2'] = 'zvfpcms/admin';
$path['root'] = 'zvfpcms';
$path['images'] = 'zvfpcms/img';
$path['css'] = 'zvfpcms/css';
$path['js'] = 'zvfpcms/js';
$path['pages'] = 'zvfpcms/pg';
?>
The thing is, I want the $cfg variable(s) to be edited directly via an interface.
How would this be achieved? I cannot think replacing strings would be a good idea especially when there are a very large number of possibilities (or even infinite) for future $cfg variables I create.
Or, will I have to settle for a different method...
Answers appreciated!
回答1:
Pear Config will let you read and write configuration easily to/from different sources, including a PHP file/array. You would probably need to move $cfg
into its own file though and include it so that other variables etc. are unaffected.
You could also do it yourself using var_export() and then writing over the file, again you would probably need to move the variable into its own file. I think that this would write messier/less readable PHP than the Pear class.
回答2:
Just have all the settings in your database, and when a setting changes, rebuild the config file.
回答3:
Don't have your PHP edit PHP code. Use an XML config file instead. Read the XML info out, if you want to make a change, change the value in the data structure generated from the XML file and spit it back out into a new config file.
回答4:
Either store the settings in a database, or you could use a standard ini-file (key=value pairs);
lang=en
timezone=CET
Read them:
function loadSettings() {
$cfg = array();
foreach (file('settings.ini') as $line) {
list ($key, $value) = explode('=', $line);
$cfg[$key] = $value;
}
return $cfg;
}
File I/O are less efficiant than standard database calls thou, especially if you already have an open connection to a database.
回答5:
The reason I believe that this IS bad practice is because you can have a running system before the edit, have some error in the edit (perhaps you didn't escape a single-quote character) and after the edit the entire application becomes unavailable because PHP can't parse the config file, which affects almost everything you do.
The XML suggestion isn't a bad one as you can handle any errors that occur while you're reading the XML.
If you had a database (reading this post it looks like you aren't using one, which is fine), that would be the best place for the data - that's what it's for. In a flat-file world, reading in a non-PHP file and interpreting it is far better than auto-editing the PHP files yourself.
来源:https://stackoverflow.com/questions/833237/editing-php-files-for-configuration-via-php