0

可能重复:
读取和写入配置文件

我的大部分功能取决于设置。

截至目前,我将我的设置值存储在数据库中。

例如,要在页面中显示广告,我正在检查我的数据库是否显示广告

我的意思是这样

$display_ad = 'get value from database';

if ($display_ad) {
echo 'Ad code goes here';
}

这可以。但事实是我有超过 100 个设置。所以我认为如果我在 settings.php 文件中定义值,我的数据库负载将会减少

define('DISPLAY_AD', true); 

if (DISPLAY_AD) {
echo 'Ad code goes here';
}

但我不确定这是正确的方法。是define()正确的解决方案。或者有没有更好更快的解决方案?

4

4 回答 4

1

几个选项,如提到的那些,包括.ini文件(使用parse_ini_file())、XML(可能与SimpleXML的一些混合物),但我更喜欢将配置保留在原生 PHP 中。

include()构造允许一个return从包含的文件。这使您可以:

配置文件

return [
    'foo' => [
        'bar' => [
            'qux' => true,
        ],
        'zip' => false,
    ],
];

别处.php

function loadConfig($file) {
    if (!is_file($file)) {
        return false;
    }
    return (array) call_user_func(function() use($file) {
        // I always re-scope for such inclusions, however PHP 5.4 introduced 
        // $this rebinding on closures so it's up to you
        return include($file);
    });
}

$config = loadConfig('config.php');

if ($config['foo']['bar']['qux']) {
    // yeop
}
if ($config['foo']['zip']) {
    // nope
}

需要特别小心,因为当您尝试取消引用不存在的维度时,PHP 会在您身上大便:

if ($config['i']['am']['not']['here']) { // poop

}

创建一个包装类/函数来管理您需要的配置是相当简单的。您可以添加对级联配置(在ASPweb.config世界中的一种)、缓存等的支持。

于 2013-01-05T15:40:12.510 回答
0

define()是相当不错的做事方式。另一种方法是定义一个全局数组。如

$config['display_ad']=true;
$config['something_else']='a value';
//...
function doSomething() {
   global $config;
   if ($config['display_ad']) echo 'Ad code goes here';
}

后一种方式是许多项目使用的方式,例如 phpmyadmin,原因可能是,您不能define()使用非标量值,例如define('SOME_ARRAY',array('a','b'))无效。

于 2013-01-05T14:54:21.480 回答
0

最简单的执行是一个ini文件。您创建一个如下所示的文件:

value1 = foo
value2 = bar
value3 = baz

然后,从 PHP 中,您可以执行以下操作:

$iniList = get_ini_file("/path/to/ini/file/you/just/made");
if ($iniList['value1'] == 'foo') {
    print "This will print because the value was set from get_ini_file."
}

如果你有很多类似的常量,那比几十个定义方法要好,比数据库获取要快。

于 2013-01-05T14:57:24.073 回答
0

你也可以在这里创建一个类: php.net

于 2013-01-05T16:28:06.473 回答