PageRenderTime 37ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/2010/end_system/library/enddb.php

http://endcms.googlecode.com/
PHP | 89 lines | 44 code | 8 blank | 37 comment | 12 complexity | 23bc182e639cdf86bb2c1bd2e4d0ee49 MD5 | raw file
  1. <?php
  2. /**
  3. * EndDB
  4. * the file system based NoSQL database
  5. */
  6. /**
  7. * EndDB
  8. * 作者: Longbill longbill.cn@gmail.com http://php.js.cn
  9. * 2011-03-04
  10. * 用法:
  11. * $enddb = new EndDB('/var/tmp');
  12. * $enddb->set('key1','string1');
  13. * $enddb->set('key2',$_COOKIE);
  14. * print_r($enddb->get('key1'));
  15. * $enddb->delete('key2');
  16. */
  17. class EndDB
  18. {
  19. public $path;
  20. public $default_type;
  21. /**
  22. * $path: EndDB数据文件存储的根目录,需要php具有读写权限
  23. * $default_type: 如果是json,那么存储和读取数据的时候默认会执行json_encode和json_decode操作,默认是json。
  24. */
  25. function EndDB($path,$default_type = 'json')
  26. {
  27. if (substr($path,-1) != '/') $path.='/';
  28. $this->path = $path;
  29. $this->default_type = $default_type;
  30. }
  31. /**
  32. * 存储数据
  33. * $key: 数据的key,可以是任意字符串,因为会被md5一次。
  34. * $data: 数据,如果$type是json,那么$data可以为array,否则只能是string
  35. * 可选 $type: 数据的类型,默认等于$this->default_type
  36. */
  37. public function set($key,$data,$type = '')
  38. {
  39. $hash = md5($key);
  40. if ($type === '') $type = $this->default_type;
  41. if ($type == 'json') $data = json_encode($data);
  42. return file_put_contents($this->_get_dir($hash),$data);
  43. }
  44. /**
  45. * 读取数据
  46. * $key: 数据的key
  47. * 可选 $type: 数据的类型,默认等于$this->default_type
  48. */
  49. public function get($key,$type = '')
  50. {
  51. $hash = md5($key);
  52. if ($type === '') $type = $this->default_type;
  53. $filename = $this->_get_dir($hash);
  54. if (!file_exists($filename)) return false;
  55. $data = file_get_contents($filename);
  56. if ($type == 'json') $data = json_decode($data,true);
  57. return $data;
  58. }
  59. /**
  60. * 删除
  61. */
  62. public function delete($key)
  63. {
  64. $hash = md5($key);
  65. $filename = $this->_get_dir($hash);
  66. if (!file_exists($filename)) return true;
  67. return unlink($filename);
  68. }
  69. /**
  70. * 内部函数,获得key对应的文件路径
  71. * 目前采用的是md5(key)的前2个字符作为一级路径,2到4个字符作为二级路径。 如果数据量比较大,可以考虑增加三级甚至四级路径。
  72. */
  73. private function _get_dir($hash)
  74. {
  75. $dir = $this->path.substr($hash, 0, 2).'/';
  76. if (!is_dir($dir)) mkdir($dir);
  77. $dir.= substr($hash,2,2).'/';
  78. if (!is_dir($dir)) mkdir($dir);
  79. return $dir.$hash;
  80. }
  81. }