perkiset

There are many ways to get "configuration" data to a site... the most common being a database or flat text file.

But both of these has the drawback of *some* type of access - TCP/IP, file system... something. I suggest that another way to do it, is to literally write values into source code of a

PHP

  file. This does NOT make sense unless you have a code-cacher running, like APC - if you don't, then you've encurred the cost of file system access (one of the most painful) and compiling the

PHP

  code again. But if you DO have APC running, then the code is already compiled and sitting in memory.

Consider this:

<?

php

 

config_Value1 = 10;
config_AnotherValue = 'This is a test';
config_MyArray = array(0=>'Hello', 1=>'World');

?>


If you were to simply include/require this code in your application, the values would be instantly available to the routine that included it. If this code were already compiled and sitting in RAM, then this becomes and extremely quick way of "configuring a site." How do we manage it though?

Regex

 es, file_get_contents and file_put_contents. Consider this function:


define('CONFIGFILE', '/www/sites/aFileName.txt');
function getConfigValue($valueName)
{
if (preg_match("/config_{$valueName}<>*=<>*(.*)$"/, file_get_contents(CONFIGFILE), $matches))
{
return $matches[1];
} else {
return false;
}
}


With this simple little example, we can see how a value could be extracted from a file and returned. Note that this does not handle case sensitivity, nor the ability to have multiple files or anything, but you get the idea. It also puts the burden of processor time on the updater  - rather than the reader. This is important: by doing it this way, it takes a little longer to read and write values to the config file - but the execution of the website will be way faster.

Writing configuration data could be easier than this, but I like this method because it creates nice orderly files every time:

define('CONFIGFILE', '/www/sites/aFileName.txt');
function setConfigValue($valueName, $aValue)
{
$lines = explode(chr(10), file_get_contents(CONFIGFILE));
foreach($lines as $line)
{
if (!preg_match('/config_([^s]+)<>*=<>*(.*$)', $line, $parts)) { continue; }
$values[$parts[1]] = $parts[2];
}
$parts[$valueName] = $aValue;
ksort($parts);
$output[] = '<?';
foreach($values as $name=>$value) { $output[] = "config_$name = $value"; }
$output[] = '?>';
file_put_contents(implode(chr(10), $output);
}


Note that this little example does not handle multi-user issues, nor even some of the more ticklish issues of what type of data is being sent and such. The handy part of APC here is that much like JBoss and other Java systems, the acto of modifying the mtime on a file will invalidate it in the cache - so the very next pull it will be recompiled and cached again - and stay that way until it is modified again.


Perkiset's Place Home   Politics @ Perkiset's