FileCache.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. /**
  3. * Cache with file system
  4. */
  5. class FileCache extends CacheAbstract{
  6. protected $cacheDirCreated; // boolean to avoid always chck dir cache existance
  7. public function loadData(){
  8. $this->isPrepareCache();
  9. $datas = json_decode(file_get_contents($this->getCacheFile()),true);
  10. $items = array();
  11. foreach($datas as $aData){
  12. $item = new \Item();
  13. foreach($aData as $name => $value){
  14. $item->$name = $value;
  15. }
  16. $items[] = $item;
  17. }
  18. return $items;
  19. }
  20. public function saveData($datas){
  21. $this->isPrepareCache();
  22. file_put_contents($this->getCacheFile(), json_encode($datas));
  23. return $this;
  24. }
  25. public function getTime(){
  26. $this->isPrepareCache();
  27. $cacheFile = $this->getCacheFile();
  28. if( file_exists($cacheFile) ){
  29. return filemtime($cacheFile);
  30. }
  31. return false;
  32. }
  33. /**
  34. * Cache is prepared ?
  35. * Note : Cache name is based on request information, then cache must be prepare before use
  36. * @return \Exception|true
  37. */
  38. protected function isPrepareCache(){
  39. if( is_null($this->param) ){
  40. throw new \Exception('Please feed "prepare" method before try to load');
  41. }
  42. return true;
  43. }
  44. /**
  45. * Return cache path (and create if not exist)
  46. * @return string Cache path
  47. */
  48. protected function getCachePath(){
  49. $cacheDir = __DIR__ . '/../cache/'; // FIXME : configuration ?
  50. // FIXME : implement recursive dir creation
  51. if( is_null($this->cacheDirCreated) && !is_dir($cacheDir) ){
  52. $this->cacheDirCreated = true;
  53. mkdir($cacheDir,0705);
  54. chmod($cacheDir,0705);
  55. }
  56. return $cacheDir;
  57. }
  58. /**
  59. * Get the file name use for cache store
  60. * @return string Path to the file cache
  61. */
  62. protected function getCacheFile(){
  63. return $this->getCachePath() . $this->getCacheName();
  64. }
  65. /**
  66. * Determines file name for store the cache
  67. * return string
  68. */
  69. protected function getCacheName(){
  70. $this->isPrepareCache();
  71. $stringToEncode = $_SERVER['REQUEST_URI'] . http_build_query($this->param);
  72. return hash('sha1', $stringToEncode) . '.cache';
  73. }
  74. }