FileCache.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. return hash('sha1', $stringToEncode) . '.cache';
  70. }
  71. }