1
0

FileCache.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 = unserialize(file_get_contents($this->getCacheFile()));
  10. return $datas;
  11. }
  12. public function saveData($datas){
  13. $this->isPrepareCache();
  14. //Re-encode datas to UTF-8
  15. //$datas = Cache::utf8_encode_deep($datas);
  16. $writeStream = file_put_contents($this->getCacheFile(), serialize($datas));
  17. if(!$writeStream) {
  18. throw new \Exception("Cannot write the cache... Do you have the right permissions ?");
  19. }
  20. return $this;
  21. }
  22. public function getTime(){
  23. $this->isPrepareCache();
  24. $cacheFile = $this->getCacheFile();
  25. if(file_exists($cacheFile)){
  26. return filemtime($cacheFile);
  27. }
  28. return false;
  29. }
  30. /**
  31. * Cache is prepared ?
  32. * Note : Cache name is based on request information, then cache must be prepare before use
  33. * @return \Exception|true
  34. */
  35. protected function isPrepareCache(){
  36. if(is_null($this->param)){
  37. throw new \Exception('Please feed "prepare" method before try to load');
  38. }
  39. return true;
  40. }
  41. /**
  42. * Return cache path (and create if not exist)
  43. * @return string Cache path
  44. */
  45. protected function getCachePath(){
  46. $cacheDir = __DIR__ . '/../cache/'; // FIXME : configuration ?
  47. // FIXME : implement recursive dir creation
  48. if(is_null($this->cacheDirCreated) && !is_dir($cacheDir)){
  49. $this->cacheDirCreated = true;
  50. mkdir($cacheDir,0705);
  51. chmod($cacheDir,0705);
  52. }
  53. return $cacheDir;
  54. }
  55. /**
  56. * Get the file name use for cache store
  57. * @return string Path to the file cache
  58. */
  59. protected function getCacheFile(){
  60. return $this->getCachePath() . $this->getCacheName();
  61. }
  62. /**
  63. * Determines file name for store the cache
  64. * return string
  65. */
  66. protected function getCacheName(){
  67. $this->isPrepareCache();
  68. $stringToEncode = $_SERVER['REQUEST_URI'] . http_build_query($this->param);
  69. $stringToEncode = preg_replace('/(\?|&)format=[^&]*/i', '$1', $stringToEncode);
  70. return hash('sha1', $stringToEncode) . '.cache';
  71. }
  72. }