背景:PHP的空文件输出
我想创建一个平面文件键值存储。当我使用下面的代码时,已经写入文件的数组被删除,并最终得到一个空文件。在下一个请求中,文件将被填充到数组中。该过程在每个页面请求上循环。
我曾尝试:
- 用各种方法 “json_encode()”/ “json_decode()”。
- 也试图用“serialize()”/“unserialize()”来做同样的事情。
- 用“array_merge()”和“array_merge_recursive()”尝试了各种编码结构。
没有什么似乎工作!我结束了一个空文件的同一回路 - >文件与阵列并继续
问:
更有经验的人能告诉我什么,我做错了什么?
代码:
/**
* Class Orm
*/
class Orm
{
/**
* @var string The Root database directory with a trailing slash. default is "./database/".
*/
static $dir = "./database/";
/**
* @var array
*/
protected $data;
/**
* @var string
*/
protected $file = "";
/**
* @param $file
* @return string
*/
public function load_table($file)
{
try {
if (file_exists(self::$dir . $file)) {
return $this->file = $file;
} else {
throw new Exception("The file " . $file . " cannot be created, because it already exists");
}
} catch (Exception $error) {
return $error->getMessage();
}
}
/**
* @param String
* @param array $values An associative array of values to store.
* @return array
*/
public function set($key, $values = array())
{
try{
if (!empty($key) && !empty($values)){
return $this->data[$key] = $values;
} else {
throw new Exception();
}
} catch (Exception $error){
return $error->getMessage();
}
}
public function save()
{
try{
if (file_exists(self::$dir . $this->file)) {
if (filesize(self::$dir . $this->file) == 0)
{
file_put_contents(self::$dir . $this->file, print_r($this->data, TRUE));
}else{
$tmp = file_get_contents(self::$dir . $this->file);
$content = array_merge($tmp, $this->data);
file_put_contents(self::$dir . $this->file, print_r($content, TRUE));
}
} else {
throw new Exception();
}
} catch(Exception $error){
return $error->getMessage();
}
}
}
$user = new Orm();
$user->load_table("users");
$user->set("Tito",array("age" => "32", "occupation" => "cont"));
$user->save();
PS:我认为这将是一个很好的项目,以自己熟悉用PHP。所以请不要建议使用SQL,因为这仅用于学习和理解Php。
+1“我试过的东西” – Kermit 2013-04-30 19:05:35