2013-04-30 55 views
2

背景: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

+1“我试过的东西” – Kermit 2013-04-30 19:05:35

回答

3

我不能说为什么你的代码无法做到这一点。不过,我会创建另一个对象,负责将字符串加载并保存到磁盘。没有更多,也没有少:

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类,而不是继续修复。

+0

谢谢你对事物的看法。它真的帮助我以不同的方式看待事情。我用清晰的头脑看了代码并阅读了函数。我在set方法和print_r返回值上犯了一个错误。 – Dany 2013-05-01 18:03:28