<?php
class config {
private $cid;
private $name;
private $value;
private $configNames = array();
public function __construct() {
$this->configNames[] = "mail_address";
$this->configNames[] = "mail_username";
$this->configNames[] = "mail_password";
$this->configNames[] = "mail_pop_host";
$this->configNames[] = "mail_pop_port";
$this->configNames[] = "mail_smtp_host";
$this->configNames[] = "mail_smtp_port";
}
//initialize the configs in database
public static function initialize() {
$newConfig = new config();
$query = sprintf('TRUNCATE TABLE %sconfig',
DB_TBL_PREFIX);
mysql_query($query);
foreach ($newConfig->configNames as $value) {
$query = sprintf('INSERT INTO %sconfig (name) VALUES ("%s")',
DB_TBL_PREFIX,
$value);
mysql_query($query);
}
}
public function __get($name) {
if ($name == "configNames") {
return $this->configNames;
}else {
$query = sprintf('SELECT value FROM %sconfig WHERE name = "%s"',
DB_TBL_PREFIX,
$name);
$result = mysql_query($query);
if (mysql_num_rows($result)) {
$row = mysql_fetch_assoc($result);
$this->value = $row['value'];
return $this->value;
}else {
echo "<strong>no this config option!</strong>";
return false;
exit;
}
}
}
public function __set($name, $value) {
if (in_array($name, $this->configNames)) {
$query = sprintf('UPDATE %sconfig SET value = "%s" WHERE name = "%s"',
DB_TBL_PREFIX,
$value,
$name);
mysql_query($query);
}else {
echo "<strong>no this config option!</strong>";
return false;
exit;
}
}
}
?>这样子就可以直接$config = new config();
//读取
$config->mail_address;
//写入
$config->mail_address = "[email protected]";这样有什么不妥的地方吗?
config没有mail_address属性
只用configName属性,而且这个属性是私有的,外部不能直接调用
我看到大多是都是赋值之后,用一个save()方法保存的。这个直接赋值即保存,而且这个是网站配置类。不用多用户多次平凡使用。所以这样我觉得很方便。
建议数据库结合php文件,文件中设置一个$config数组,比如$config['mail_address'] = '[email protected]';
调用时直接引入文件,取值直接读。写入时插入数据库,生成文件,一般配置的东西更改少,查询多。
http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members
我感觉这样写扩展以及使用都很方便。
还有“建议数据库结合php文件,文件中设置一个$config数组,比如$config['mail_address'] = '[email protected]';
调用时直接引入文件,取值直接读。写入时插入数据库,生成文件,一般配置的东西更改少,查询多。”
这一段不太明白呢?能不能说详细一点。谢谢~
类的定义没错,是通过__get和__set方法来做的.
那我就加一个方法,一次性读完所有的参数。这样行吗?
这样前台调用就不用很多的select了。
不知道我是否理解了?cunningboy ?
function __construct(){
}
function __get($name){
return $GLOBALS['config'][$name];
}
function __set($name){
//update sql
if($updateSuccess){
//select * from config,然后重新生成config.php文件。
}
}
}