如何创建全局配置文件


How to create global configuration file?

是否有可能使用类中可见的全局变量创建配置文件?类似于这样的东西:

配置.php:

$config['host_address'] = 'localhost';
$config['username '] = 'root';
$config['password'] = 'root';
$config['name'] = 'data';

分贝.php:

include('config.php');
class DB
{
    private $_config = array($config['host_address'], $config['username'], $config['password'], $config['name']);
    ...

当前属性:

private $ _config = array();

我不想通过构造函数传输到我的单一实例数据库连接器:

DB::getInstance(array('localhost', 'root', 'root', 'data'));

每个人都有自己的喜好。我更喜欢将我的数据库设置存储在 webroot 之外的.ini中,然后给它一个 0600 chmod 值,以防止除了所有者之外的任何人读取它。

示例.ini如下所示:

[database]
driver = mysql
host = localhost
;port = 3306
schema = yourdbname
username = dbusername
password = some_pass

然后你可以使用 php 函数parse_ini_file然后在你的构造函数中读取它并将其解析成一个数组:

public function __construct($file = 'dbsettings.ini')
{
    // @todo: change this path to be consistent with outside your webroot
    $file = '../' . $file;
    if (!$settings = parse_ini_file($file, TRUE)) throw new exception('Unable to open ' . $file . '.');
    $dns = $settings['database']['driver'] .
    ':host=' . $settings['database']['host'] .
    ((!empty($settings['database']['port'])) ? (';port=' . $settings['database']['port']) : '') .
    ';dbname=' . $settings['database']['schema'];
    // if not PDO, this part needs to be changed parent::__construct($dns, $settings['database']['username'], $settings['database']['password']);
}

和中提琴,您有一种简单而安全的方式来设置数据库连接。这个类取自PDO扩展器类,所以如果你不使用PDO,你需要改变那一行,但正如你可以看到的,你在$settings数组中获取用户名等。

我会高度避免将任何类型的数据库信息存储到 CONSTANTGLOBAL 类型变量中。这样,$settings只能用于该类函数,而不能用于其他函数,从而提供了额外的安全层。

您的问题是您尝试在此处的类定义中使用表达式

class DB
{
    private $_config = array($config['host_address'], ...

这在语法上是不正确的(您只能为此使用常量值),我不希望它在那里找到预期范围。相反,您应该做的是在构造器中初始化此属性:

class DB
{
    private $_config;
    function __construct() {
        global $config;
        $this->_config = array($config['host_address'], $config['username'], $config['password'], $config['name']);
    }

或者更懒惰,只需使用 include('config.php'); 代替global $config别名即可。这样,您的配置脚本将$config提取为构造函数中的局部变量,这就是您所需要的。

您可以尝试定义:

define('host_address', 'root');
define('username', 'root');

'用法:

DB::getInstance(array(host_address, username, ...));