SimpleDB.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. <?php
  2. /****************************************************
  3. * NKeditor PHP
  4. * 本PHP程序是演示程序,建议不要直接在实际项目中使用。
  5. * 如果您确定直接使用本程序,使用之前请仔细确认相关安全设置。
  6. * **************************************************
  7. * 简易数据库, 单表 100w 条数据,查询一页数据在 0.015 秒左右
  8. * 缺陷,无法排序,如果要排序的话,那么不适合使用 SimpleDB, 请使用 mysql 或者 mongdb
  9. * User: yangjian
  10. * Date: 17-10-14
  11. * Time: 下午5:15
  12. */
  13. class SimpleDB {
  14. /**
  15. * 文件资源
  16. * @var null|resource
  17. */
  18. private $handler = null;
  19. /**
  20. * 初始化,打开文件
  21. * SimpleDB constructor.
  22. * @param $dbname
  23. */
  24. public function __construct($dbname)
  25. {
  26. $dataDir = __DIR__."/data/";
  27. if (!file_exists($dataDir)) {
  28. mkdir($dataDir);
  29. }
  30. $this->handler = fopen($dataDir.$dbname.'.db', 'a+');
  31. }
  32. /**
  33. * 写入一行数据
  34. * @return bool
  35. */
  36. public function putLine($data) {
  37. if ($this->handler != null) {
  38. fwrite($this->handler, $this->seralize($data));
  39. }
  40. return false;
  41. }
  42. /**
  43. * 分页获取数据列表
  44. * @param $key
  45. * @return array|null
  46. */
  47. public function getDataList($page, $pagesize) {
  48. if($page <= 0) {
  49. $page = 1;
  50. }
  51. $offset = ($page - 1) * $pagesize;
  52. //循环读取数据
  53. $datas = [];
  54. $counter = 0;
  55. while (!feof($this->handler)) {
  56. if ($counter < $offset) {
  57. fgets($this->handler); //移动指针到下一行
  58. $counter++;
  59. continue;
  60. }
  61. if (count($datas) == $pagesize) {
  62. break;
  63. }
  64. $line = fgets($this->handler);
  65. if (!empty($line)) {
  66. $datas[] = $this->unseralize($line);
  67. }
  68. }
  69. return $datas;
  70. }
  71. /**
  72. * 序列化数据
  73. * @param $data
  74. * @return string
  75. */
  76. private function seralize($data) {
  77. $break = "\n"; //换行符
  78. if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
  79. $break = "\r\n";
  80. }
  81. return json_encode($data, JSON_UNESCAPED_UNICODE).$break;
  82. }
  83. /**
  84. * 反序列化
  85. * @param $data
  86. * @return mixed
  87. */
  88. private function unseralize($data) {
  89. return json_decode($data, true);
  90. }
  91. /**
  92. * 关闭文件
  93. */
  94. public function __destruct()
  95. {
  96. if ($this->handler != null) {
  97. fclose($this->handler);
  98. }
  99. }
  100. }