开发者

Environment dependent values

Sometimes I need to use a value that is dynamic i开发者_如何转开发n a way that it would be different depending on whether the code is executed on a testing environment or a remote host.

To address that I've been using the following function:

function localhost($local_host_value, $remote_host_value = "")
{
   if($_SERVER["REMOTE_ADDR"] == "127.0.0.1")
   {
      return $local_host_value;
   }
   else
   {
      return $remote_host_value;
   }
}

Could you suggest a more elegant approach or at least a better name for the above quoted function?


I think this approach is not optimal in the long run, as all the settings are distributed all over your code, and it's very hard to e.g. add a third server environment (say, a live staging server).

I would consider using a central configuration of some sort that loads all configuration values at one point depending on which server it is running on.

Related:

  • What's Is the Best File Format for Configuration Files
  • PHP: optimum configuration storage ?


you can try getenv('REMOTE_ADDR'); if you dis-like using super-global variables

// Example use of getenv()
$ip = getenv('REMOTE_ADDR');

// Or simply use a Superglobal ($_SERVER or $_ENV)
$ip = $_SERVER['REMOTE_ADDR'];

as for the function name

function is_localhost(...)    <-- more like determine is local host (boolean)

function get_host_value(...)  <-- (string)


function localhost($local_host_value, $remote_host_value = '') {
    return $_SERVER['REMOTE_ADDR'] == '127.0.0.1'? $local_host_value : $remote_host_value;
}

Is more concise and clean in my opinion, but does just the same. Or with getenv as ajreal suggests:

function localhost($local_host_value, $remote_host_value = '') {
    return getenv('REMOTE_ADDR') == '127.0.0.1'? $local_host_value : $remote_host_value;
}

About the function name, maybe get_host_value(...) would be my choice

PS: try to use single quotes instead of double quotes when your string does not contain variables: Is there a performance benefit single quote vs double quote in php?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜