题
在 PHP 中创建平面文件数据库结构的最佳实践是什么?
我看到的许多更成熟的 PHP 平面文件框架都尝试实现类似 SQL 的查询语法,这在大多数情况下超出了我的目的(此时我只会使用数据库)。
是否有任何优雅的技巧可以通过少量的代码开销获得良好的性能和功能?
解决方案
那么,扁平数据库的本质是什么?它们是大还是小。是里面有数组的简单数组吗?如果它很简单,那么用户配置文件是这样构建的:
$user = array("name" => "dubayou",
"age" => 20,
"websites" => array("dubayou.com","willwharton.com","codecream.com"),
"and_one" => "more");
并保存或更新 数据库记录 对于该用户。
$dir = "../userdata/"; //make sure to put it bellow what the server can reach.
file_put_contents($dir.$user['name'],serialize($user));
并加载 记录 对于用户
function &get_user($name){
return unserialize(file_get_contents("../userdata/".$name));
}
但同样,此实现将根据您所需的应用程序和数据库的性质而有所不同。
其他提示
你可能会考虑 SQLite. 。它几乎与平面文件一样简单,但您确实可以获得一个用于查询的 SQL 引擎。它 与 PHP 配合良好 也。
在我看来,从您的意思(以及您接受的答案)的意义上使用“平面文件数据库”不一定是解决问题的最佳方法。首先,使用 serialize()
和 unserialize()
如果有人进入并编辑文件,可能会引起严重的头痛(事实上,他们可以将任意代码放入您的“数据库”中以便每次运行。)
就我个人而言,我会说——为什么不展望未来呢?有很多次我遇到了问题,因为我一直在创建自己的“专有”文件,并且该项目已经爆炸到需要数据库的地步,我在想“你知道,我希望我写这个是为了数据库”——因为代码的重构需要太多的时间和精力。
从这里我了解到,让我的应用程序面向未来,这样当它变得更大时,我就不必花费数天的时间进行重构,这才是前进的方向。我该怎么做呢?
SQLite。它作为数据库工作,使用 SQL,并且很容易转换为 mySQL(特别是如果您像我一样使用抽象类进行数据库操作!)
事实上,特别是使用“接受的答案”的方法,它可以大大减少应用程序的内存使用量(您不必将所有“记录”加载到 PHP 中)
我正在考虑的一个框架是博客平台。由于您想要的任何可能的数据视图都会按日期排序,因此我正在考虑这种结构:
每个内容节点一个目录:
./content/YYYYMMDDHHMMSS/
每个节点的子目录包括
/tags
/authors
/comments
以及节点目录中用于预渲染和后渲染内容等的简单文本文件。
这将允许一个简单的 PHP glob()
调用(可能是结果数组的反转)来查询内容结构中的几乎所有内容:
glob("content/*/tags/funny");
将返回包括所有标记为“有趣”的文章的路径。
这是我们为 Lilina 使用的代码:
<?php
/**
* Handler for persistent data files
*
* @author Ryan McCue <cubegames@gmail.com>
* @package Lilina
* @version 1.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/
/**
* Handler for persistent data files
*
* @package Lilina
*/
class DataHandler {
/**
* Directory to store data.
*
* @since 1.0
*
* @var string
*/
protected $directory;
/**
* Constructor, duh.
*
* @since 1.0
* @uses $directory Holds the data directory, which the constructor sets.
*
* @param string $directory
*/
public function __construct($directory = null) {
if ($directory === null)
$directory = get_data_dir();
if (substr($directory, -1) != '/')
$directory .= '/';
$this->directory = (string) $directory;
}
/**
* Prepares filename and content for saving
*
* @since 1.0
* @uses $directory
* @uses put()
*
* @param string $filename Filename to save to
* @param string $content Content to save to cache
*/
public function save($filename, $content) {
$file = $this->directory . $filename;
if(!$this->put($file, $content)) {
trigger_error(get_class($this) . " error: Couldn't write to $file", E_USER_WARNING);
return false;
}
return true;
}
/**
* Saves data to file
*
* @since 1.0
* @uses $directory
*
* @param string $file Filename to save to
* @param string $data Data to save into $file
*/
protected function put($file, $data, $mode = false) {
if(file_exists($file) && file_get_contents($file) === $data) {
touch($file);
return true;
}
if(!$fp = @fopen($file, 'wb')) {
return false;
}
fwrite($fp, $data);
fclose($fp);
$this->chmod($file, $mode);
return true;
}
/**
* Change the file permissions
*
* @since 1.0
*
* @param string $file Absolute path to file
* @param integer $mode Octal mode
*/
protected function chmod($file, $mode = false){
if(!$mode)
$mode = 0644;
return @chmod($file, $mode);
}
/**
* Returns the content of the cached file if it is still valid
*
* @since 1.0
* @uses $directory
* @uses check() Check if cache file is still valid
*
* @param string $id Unique ID for content type, used to distinguish between different caches
* @return null|string Content of the cached file if valid, otherwise null
*/
public function load($filename) {
return $this->get($this->directory . $filename);
}
/**
* Returns the content of the file
*
* @since 1.0
* @uses $directory
* @uses check() Check if file is valid
*
* @param string $id Filename to load data from
* @return bool|string Content of the file if valid, otherwise null
*/
protected function get($filename) {
if(!$this->check($filename))
return null;
return file_get_contents($filename);
}
/**
* Check a file for validity
*
* Basically just a fancy alias for file_exists(), made primarily to be
* overriden.
*
* @since 1.0
* @uses $directory
*
* @param string $id Unique ID for content type, used to distinguish between different caches
* @return bool False if the cache doesn't exist or is invalid, otherwise true
*/
protected function check($filename){
return file_exists($filename);
}
/**
* Delete a file
*
* @param string $filename Unique ID
*/
public function delete($filename) {
return unlink($this->directory . $filename);
}
}
?>
它将每个条目存储为单独的文件,我们发现该文件的使用效率足够高(不会加载不需要的数据,并且保存速度更快)。
如果您要使用平面文件来保存数据,请使用 XML 来构建数据。PHP 有一个 内置 XML 解析器.
我编写了两个简单的函数,旨在将数据存储在文件中。您可以自行判断在这种情况下它是否有用。重点是将 php 变量(如果它是数组、字符串或对象)保存到文件中。
<?php
function varname(&$var) {
$oldvalue=$var;
$var='AAAAB3NzaC1yc2EAAAABIwAAAQEAqytmUAQKMOj24lAjqKJC2Gyqhbhb+DmB9eDDb8+QcFI+QOySUpYDn884rgKB6EAtoFyOZVMA6HlNj0VxMKAGE+sLTJ40rLTcieGRCeHJ/TI37e66OrjxgB+7tngKdvoG5EF9hnoGc4eTMpVUDdpAK3ykqR1FIclgk0whV7cEn/6K4697zgwwb5R2yva/zuTX+xKRqcZvyaF3Ur0Q8T+gvrAX8ktmpE18MjnA5JuGuZFZGFzQbvzCVdN52nu8i003GEFmzp0Ny57pWClKkAy3Q5P5AR2BCUwk8V0iEX3iu7J+b9pv4LRZBQkDujaAtSiAaeG2cjfzL9xIgWPf+J05IQ==';
foreach($GLOBALS as $var_name => $value) {
if ($value === 'AAAAB3NzaC1yc2EAAAABIwAAAQEAqytmUAQKMOj24lAjqKJC2Gyqhbhb+DmB9eDDb8+QcFI+QOySUpYDn884rgKB6EAtoFyOZVMA6HlNj0VxMKAGE+sLTJ40rLTcieGRCeHJ/TI37e66OrjxgB+7tngKdvoG5EF9hnoGc4eTMpVUDdpAK3ykqR1FIclgk0whV7cEn/6K4697zgwwb5R2yva/zuTX+xKRqcZvyaF3Ur0Q8T+gvrAX8ktmpE18MjnA5JuGuZFZGFzQbvzCVdN52nu8i003GEFmzp0Ny57pWClKkAy3Q5P5AR2BCUwk8V0iEX3iu7J+b9pv4LRZBQkDujaAtSiAaeG2cjfzL9xIgWPf+J05IQ==')
{
$var=$oldvalue;
return $var_name;
}
}
$var=$oldvalue;
return false;
}
function putphp(&$var, $file=false)
{
$varname=varname($var);
if(!$file)
{
$file=$varname.'.php';
}
$pathinfo=pathinfo($file);
if(file_exists($file))
{
if(is_dir($file))
{
$file=$pathinfo['dirname'].'/'.$pathinfo['basename'].'/'.$varname.'.php';
}
}
file_put_contents($file,'<?php'."\n\$".$varname.'='.var_export($var, true).";\n");
return true;
}
如果你想要一个人类可读的结果,你也可以使用这种类型的文件:
ofaurax|27|male|something|
another|24|unknown||
...
这样,您只有一个文件,您可以轻松地调试它(并手动修复),您可以稍后添加字段(在每一行的末尾),并且 PHP 代码很简单(对于每一行,根据 | 分割)。
然而,缺点是您应该解析整个文件来搜索某些内容(如果您有数百万个条目,那就不好了)并且您应该处理数据中的分隔符(例如,如果昵称是 War|ordz)。
这是一个鼓舞人心的实用解决方案:
https://github.com/mhgolkar/FlatFire
它使用多种策略来处理数据......
[从自述文件复制]
自由、结构化或混合
- STRUCTURED
Regular (table, row, column) format.
[DATABASE]
/ \
TX TableY
\_____________________________
|ROW_0 Colum_0 Colum_1 Colum_2|
|ROW_1 Colum_0 Colum_1 Colum_2|
|_____________________________|
- FREE
More creative data storing. You can store data in any structure you want for each (free) element, its similar to storing an array with a unique "Id".
[DATABASE]
/ \
EX ElementY (ID)
\________________
|Field_0 Value_0 |
|Field_1 Value_1 |
|Field_2 Value_2 |
|________________|
recall [ID]: get_free("ElementY") --> array([Field_0]=>Value_0,[Field_1]=>Value_1...
- MIXD (Mixed)
Mixed databases can store both free elements and tables.If you add a table to a free db or a free element to a structured db, flat fire will automatically convert FREE or SRCT to MIXD database.
[DATABASE]
/ \
EX TY
只是指出此类系统的平面文件数据库的潜在问题:
data|some text|more data
row 2 data|bla hbalh|more data
...ETC
问题是单元数据包含一个“ |”或“ n”,那么数据将丢失。有时,通过大多数人不会使用的字母组合来分割会更容易。
例如:
列分离器: #$% (Shift+345)
行分割器: ^&* (Shift+678)
文本文件: test data#$%blah blah#$%^&*new row#$%new row data 2
然后使用: explode("#$%", $data); use foreach, the explode again to separate columns
或者任何类似的事情。另外,我可能会补充一点,平面文件数据库适合具有少量数据的系统(即。少于 20 行),但对于较大的数据库来说会占用大量内存。