在PHP中创建配置文件
我想为我的PHP项目创建一个配置文件,但我不确定最好的方法是什么 到目前为止,我有3个想法 1-使用变量在PHP中创建配置文件,php,configuration-files,Php,Configuration Files,我想为我的PHP项目创建一个配置文件,但我不确定最好的方法是什么 到目前为止,我有3个想法 1-使用变量 $config['hostname'] = "localhost"; $config['dbuser'] = "dbuser"; $config['dbpassword'] = "dbpassword"; $config['dbname'] = "dbname"; $config['sitetitle'] = "sitetitle"; 2-Use Const define('DB_NAME
$config['hostname'] = "localhost";
$config['dbuser'] = "dbuser";
$config['dbpassword'] = "dbpassword";
$config['dbname'] = "dbname";
$config['sitetitle'] = "sitetitle";
2-Use Const
define('DB_NAME', 'test');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('TITLE', 'sitetitle');
3用数据库
$config['hostname'] = "localhost";
$config['dbuser'] = "dbuser";
$config['dbpassword'] = "dbpassword";
$config['dbname'] = "dbname";
$config['sitetitle'] = "sitetitle";
我将在类中使用配置,因此我不确定哪种方法最好,或者是否有更好的方法。我通常会创建一个包含数据库连接的conn.php文件。
然后我将该文件包括在所有需要数据库查询的文件中 Define将使常量在类中的任何位置都可用,而不需要使用global,而变量在类中需要global,我将使用Define。但同样,如果db参数在程序执行期间发生变化,您可能希望继续使用变量。好吧-将数据库配置数据存储在数据库中有点困难-您不这么认为吗 但事实上,这是一个非常固执己见的问题,因为任何风格都是有效的,这都是偏好的问题。就我个人而言,我会选择配置变量而不是常量——通常是因为我不喜欢全局空间中的东西,除非必要。我的代码库中没有一个函数能够轻松访问我的数据库密码(数据库连接逻辑除外)——因此我会在那里使用它,然后可能会销毁它
编辑:回答您的评论-没有一种解析机制是最快的(ini、json等)-但它们也不是您真正需要重点优化的应用程序部分,因为在这样小的文件上,速度差异可以忽略不计。如果您认为出于任何原因将使用超过1 db的数据,请使用该变量,因为您可以更改一个参数以切换到完全不同的db。例如,用于测试、自动备份等。一种简单而优雅的方法是创建一个只返回数组的
config.php
文件(或您所称的任何文件):
<?php
return array(
'host' => 'localhost',
'username' => 'root',
);
这是我的路
<?php
define('DEBUG',0);
define('PRODUCTION',1);
#development_mode : DEBUG / PRODUCTION
$development_mode = PRODUCTION;
#Website root path for links
$app_path = 'http://192.168.0.234/dealer/';
#User interface files path
$ui_path = 'ui/';
#Image gallery path
$gallery_path = 'ui/gallery/';
$mysqlserver = "localhost";
$mysqluser = "root";
$mysqlpass = "";
$mysqldb = "dealer_plus";
?>
如有任何疑问,请发表意见使用INI文件是一种灵活而强大的解决方案!PHP必须正确处理它。例如,可以创建如下所示的INI文件: 应用程序ini
[database]
db_name = mydatabase
db_user = myuser
db_password = mypassword
[application]
app_email = mailer@myapp.com
app_url = myapp.com
因此,您唯一需要做的就是打电话:
$ini = parse_ini_file('app.ini');
然后,您可以使用$ini
数组轻松访问定义
echo $ini['db_name']; // mydatabase
echo $ini['db_user']; // myuser
echo $ini['db_password']; // mypassword
echo $ini['app_email']; // mailer@myapp.com
重要提示:出于安全原因,INI文件必须位于非公共文件夹中我使用了@hugo_leonardo的一些改进: 以上假设您的
config.php
包含app\u info
参数:
<?php
return (object) array(
'host' => 'localhost',
'username' => 'root',
'pass' => 'password',
'database' => 'db',
'app_info' => array(
'appName'=>"App Name",
'appURL'=> "http://yourURL/#/"
)
);
?>
因此,您的数据库信息保留在服务器端,但您的应用程序信息可以从JavaScript访问,例如使用
$http.get('get_app_info.php')。然后(…)代码>通话类型。我看到的具有相对优点/缺点的选项有:
基于文件的机制
这些要求您的代码在特定位置查找ini文件。这是一个很难解决的问题,并且在大型PHP应用程序中经常出现。然而,为了找到在运行时被合并/重用的PHP代码,您可能需要解决这个问题
常用的方法是始终使用相对目录,或者从当前目录向上搜索,以在应用程序的基本目录中找到一个以独占方式命名的文件
用于配置文件的常见文件格式有PHP代码、ini格式文件、JSON、XML、YAML和序列化PHP
PHP代码
$config['hostname'] = "localhost";
$config['dbuser'] = "dbuser";
$config['dbpassword'] = "dbpassword";
$config['dbname'] = "dbname";
$config['sitetitle'] = "sitetitle";
这为表示不同的数据结构提供了巨大的灵活性,并且(假设它是通过include或require处理的)解析的代码可以从操作码缓存中获得,从而提高了性能
提供了一种方法来抽象文件的潜在位置,而无需依赖其他代码
另一方面,将配置与代码分离的主要原因之一是将责任分离。它提供了向运行时注入额外代码的路径
如果配置是从工具创建的,则可以验证工具中的数据,但是没有标准函数可以转义数据以嵌入到PHP代码中,因为HTML、URL、MySQL语句、shell命令
序列化数据
这对于少量的配置(最多200项)来说是相对有效的,并且允许使用任何PHP数据结构。创建/解析数据文件只需要很少的代码(因此,您可以将精力放在确保仅在获得适当授权的情况下编写文件上)
写入文件的内容转义将自动处理
由于您可以序列化对象,因此只需通过读取配置文件(_uuuwakeup magic方法)即可创建调用代码的机会
结构化文件
$config['hostname'] = "localhost";
$config['dbuser'] = "dbuser";
$config['dbpassword'] = "dbpassword";
$config['dbname'] = "dbname";
$config['sitetitle'] = "sitetitle";
将其存储为Marcel或JSON或XML建议的INI文件还提供了一个简单的api,用于将文件映射到PHP数据结构(除XML外,用于转义数据并创建文件),同时消除使用序列化PHP数据的代码调用漏洞
它将具有与序列化数据类似的性能特征
数据库存储
$config['hostname'] = "localhost";
$config['dbuser'] = "dbuser";
$config['dbpassword'] = "dbpassword";
$config['dbname'] = "dbname";
$config['sitetitle'] = "sitetitle";
如果您有大量的配置,但对当前任务所需的内容是有选择性的,那么最好考虑这一点——我惊讶地发现,对于大约150个数据项,从本地MySQL实例检索数据比取消序列化数据文件更快
OTOH这不是一个存储用于连接数据库的凭据的好地方
执行环境
define('DB_NAME', 'test');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('TITLE', 'sitetitle');
您可以在运行的PHP中设置值
这消除了任何需求
$dataSource = 'mysql' // or 'json'
class Config
{
// ....
static $dataSource = 'mysql';
/ .....
}
class AppConfig
{
private static $instance;
private $dataSource;
private function __construct()
{
$this->init();
}
private function init()
{
switch (Config::$dataSource)
{
case 'mysql':
$this->dataSource = new StorageMysql();
break;
case 'json':
$this->dataSource = new StorageJson();
break;
default:
$this->dataSource = new StorageMysql();
}
}
public static function getInstance()
{
if (empty(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
public function getDataSource()
{
return $this->dataSource;
}
}
$container->getItemsLoader(AppConfig::getInstance()->getDataSource()) // getItemsLoader need Object of specific data source class by dependency injection
class Configuration
{
private $config;
public function __construct($configIniFilePath)
{
$this->config = parse_ini_file($configIniFilePath, true);
}
/**
* Gets the value for the specified setting name.
*
* @param string $name the setting name
* @param string $section optional, the name of the section containing the
* setting
* @return string|null the value of the setting, or null if it doesn't exist
*/
public function getConfiguration($name, $section = null)
{
$configValue = null;
if ($section === null) {
if (array_key_exists($name, $this->config)) {
$configValue = $this->config[$name];
}
} else {
if (array_key_exists($section, $this->config)) {
$sectionSettings = $this->config[$section];
if (array_key_exists($name, $sectionSettings)) {
$configValue = $sectionSettings[$name];
}
}
}
return $configValue;
}
}
user=cacom
version = 2021608
status= true
function readFileConfig($UrlOrFilePath){
$lines = file($UrlOrFilePath);
$config = array();
foreach ($lines as $l) {
preg_match("/^(?P<key>.*)=(\s+)?(?P<value>.*)/", $l, $matches);
if (isset($matches['key'])) {
$config[trim($matches['key'])] = trim($matches['value']);
}
}
return $config;
}
$urlRemote = 'http://example.com/default-config.conf';
$localConfigFile = "/home/domain/public_html/config.conf";
$localConfigFile2 = "config.conf";
print_r(readFileConfig($localConfigFile2));
print_r(readFileConfig($localConfigFile));
print_r(readFileConfig($urlRemote));