File.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. namespace GatewayWorker\Lib\StoreDriver;
  3. /**
  4. *
  5. * 这里用php数组文件来存储数据,
  6. * 为了获取高性能需要用类似memcache的存储
  7. * @author walkor <walkor@workerman.net>
  8. *
  9. */
  10. class File
  11. {
  12. // 为了避免频繁读取磁盘,增加了缓存机制
  13. protected $dataCache = array();
  14. // 上次缓存时间
  15. protected $lastCacheTime = 0;
  16. // 打开文件的句柄
  17. protected $dataFileHandle = null;
  18. /**
  19. * 构造函数
  20. * @param 配置名 $config_name
  21. */
  22. public function __construct($config_name)
  23. {
  24. if(!is_dir(\Config\Store::$storePath) && !@mkdir(\Config\Store::$storePath, 0777, true))
  25. {
  26. // 可能目录已经被其它进程创建
  27. clearstatcache();
  28. if(!is_dir(\Config\Store::$storePath))
  29. {
  30. // 避免狂刷日志
  31. sleep(1);
  32. throw new \Exception('cant not mkdir('.\Config\Store::$storePath.')');
  33. }
  34. }
  35. $this->dataFileHandle = fopen(__FILE__, 'r');
  36. if(!$this->dataFileHandle)
  37. {
  38. throw new \Exception("can not fopen dataFileHandle");
  39. }
  40. }
  41. /**
  42. * 设置
  43. * @param string $key
  44. * @param mixed $value
  45. * @param int $ttl
  46. * @return number
  47. */
  48. public function set($key, $value, $ttl = 0)
  49. {
  50. return file_put_contents(\Config\Store::$storePath.'/'.$key, serialize($value), LOCK_EX);
  51. }
  52. /**
  53. * 读取
  54. * @param string $key
  55. * @param bool $use_cache
  56. * @return Ambigous <NULL, multitype:>
  57. */
  58. public function get($key, $use_cache = true)
  59. {
  60. $ret = @file_get_contents(\Config\Store::$storePath.'/'.$key);
  61. return $ret ? unserialize($ret) : null;
  62. }
  63. /**
  64. * 删除
  65. * @param string $key
  66. * @return number
  67. */
  68. public function delete($key)
  69. {
  70. return @unlink(\Config\Store::$storePath.'/'.$key);
  71. }
  72. /**
  73. * 自增
  74. * @param string $key
  75. * @return boolean|multitype:
  76. */
  77. public function increment($key)
  78. {
  79. flock($this->dataFileHandle, LOCK_EX);
  80. $val = $this->get($key);
  81. $val = !$val ? 1 : ++$val;
  82. file_put_contents(\Config\Store::$storePath.'/'.$key, serialize($val));
  83. flock($this->dataFileHandle, LOCK_UN);
  84. return $val;
  85. }
  86. /**
  87. * 清零销毁存储数据
  88. */
  89. public function destroy()
  90. {
  91. }
  92. }