php無數據庫讀寫配置
做小網站,或者業務中無需數據庫的網站,常常需要一些配置項,如果爲了配置這些參數使用數據庫實在是太麻煩,這裏記錄下配置文件的修改
實現邏輯
- 程序中使用一個文件用來存儲配置參數,如:“config.php”
- “config.php”文件中存儲json格式的參數
- 對“config.php”文件進行讀寫,以達到讀寫配置的目的
參見
示例代碼
GitHub地址:無數據庫讀寫配置
主要代碼
config.class.php
<?php
define('CONFIG_EXIT', '<?php exit;?>');
class Config {
private $data;
private $file;
/**
* 構造函數
* @param $file 存儲數據文件
* @return
*/
function __construct($file) {
$file = $file . '.php';
$this->file = $file;
$this->data = self::read($file);
}
/**
* 讀取配置文件
* @param $file 要讀取的數據文件
* @return 讀取到的全部數據信息
*/
public function read($file) {
if (!file_exists($file)) return array();
$str = file_get_contents($file);
$str = substr($str, strlen(CONFIG_EXIT));
$data = json_decode($str, true);
if (is_null($data)) return array();
return $data;
}
/**
* 獲取指定項的值
* @param $key 要獲取的項名
* @param $default 默認值
* @return data
*/
public function get($key = null, $default = '') {
if (is_null($key)) return $this->data; // 取全部數據
if (isset($this->data[$key])) return $this->data[$key];
return $default;
}
/**
* 設置指定項的值
* @param $key 要設置的項名
* @param $value 值
* @return null
*/
public function set($key, $value) {
if (is_string($key)) { // 更新單條數據
$this->data[$key] = $value;
} else if (is_array($key)) { // 更新多條數據
foreach ($this->data as $k => $v) {
if ($v[$key[0]] == $key[1]) {
$this->data[$k][$value[0]] = $value[1];
}
}
}
return $this;
}
/**
* 刪除並清空指定項
* @param $key 刪除項名
* @return null
*/
public function delete($key) {
unset($this->data[$key]);
return $this;
}
/**
* 保存配置文件
* @param $file 要保存的數據文件
* @return true-成功 其它-保存失敗原因
*/
public function save() {
if (defined('JSON_PRETTY_PRINT')) {
$jsonStr = json_encode($this->data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
} else {
$jsonStr = json_encode($this->data);
}
// 含有二進制或非utf8字符串對應檢測
if (is_null($jsonStr)) return '數據文件有誤';
$buffer = CONFIG_EXIT . $jsonStr;
$file_strm = fopen($this->file, 'w');
if (!$file_strm) return '寫入文件失敗,請賦予 ' . $file . ' 文件寫權限!';
fwrite($file_strm, $buffer);
fclose($file_strm);
return true;
}
}