背景:
我正在尝试创建一个平面文件键值存储。当我使用下面的代码时,已写入文件的数组将被删除,最后我得到一个空文件。在下一个请求中,该文件将填充数组。这个过程在每个页面请求上都会循环。
我尝试过的:
- 使用"json_encode(("/"json_decode(("的各种方法
- 还尝试对"serialize(("/"unserialize((("执行同样的操作
- 尝试了使用"array_merge(("answers"array_marge_recurive(("的各种编码结构
似乎什么都不管用!我最终得到了一个空文件的相同循环->带有数组的文件,它继续
问题:
有经验的人能告诉我我做错了什么吗?
代码:
/**
* 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();
附言:我认为这将是一个很好的项目,以熟悉博士。因此,请不要建议使用SQL,因为这只是为了学习和理解Php。
我不能说明为什么您的代码不能做到这一点。然而,我也会创建另一个对象,负责将字符串加载并保存到磁盘。没有更多也没有更少:
class StringStore
{
private $path;
public function __construct($path) {
$this->path = $path;
}
/**
* @return string
*/
public function load() {
... move your load code in here
return $buffer;
}
/**
* @param string $buffer
*/
public function save($buffer) {
... move your save code in here
}
}
这看起来可能有点少,但是您可以将大部分代码移出ORM类。如果问题是存储到磁盘(例如,可能犯了一些错误?(,那么您可以在存储类中修复它。
如果错误是在字符串处理中犯的,那么您知道需要查找ORM类来继续修复。