Cache.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. /**
  3. * All cache logic
  4. * Note : adapter are store in other place
  5. */
  6. interface CacheInterface{
  7. public function loadData();
  8. public function saveData($datas);
  9. public function getTime();
  10. }
  11. abstract class CacheAbstract implements CacheInterface{
  12. protected $param;
  13. public function prepare(array $param){
  14. $this->param = $param;
  15. return $this;
  16. }
  17. }
  18. class Cache{
  19. static protected $dirCache;
  20. public function __construct(){
  21. throw new \LogicException('Please use ' . __CLASS__ . '::create for new object.');
  22. }
  23. static public function create($nameCache){
  24. if( !static::isValidNameCache($nameCache) ){
  25. throw new \InvalidArgumentException('Name cache must be at least one uppercase follow or not by alphanumeric or dash characters.');
  26. }
  27. $pathCache = self::getDir() . $nameCache . '.php';
  28. if( !file_exists($pathCache) ){
  29. throw new \Exception('The cache you looking for does not exist.');
  30. }
  31. require_once $pathCache;
  32. return new $nameCache();
  33. }
  34. static public function setDir($dirCache){
  35. if( !is_string($dirCache) ){
  36. throw new \InvalidArgumentException('Dir cache must be a string.');
  37. }
  38. if( !file_exists($dirCache) ){
  39. throw new \Exception('Dir cache does not exist.');
  40. }
  41. self::$dirCache = $dirCache;
  42. }
  43. static public function getDir(){
  44. $dirCache = self::$dirCache;
  45. if( is_null($dirCache) ){
  46. throw new \LogicException(__CLASS__ . ' class need to know cache path !');
  47. }
  48. return $dirCache;
  49. }
  50. static public function isValidNameCache($nameCache){
  51. return preg_match('@^[A-Z][a-zA-Z0-9-]*$@', $nameCache);
  52. }
  53. static public function purge() {
  54. $cacheTimeLimit = time() - 60*60*24 ;
  55. $cachePath = 'cache';
  56. if(file_exists($cachePath)) {
  57. $cacheIterator = new RecursiveIteratorIterator(
  58. new RecursiveDirectoryIterator($cachePath),
  59. RecursiveIteratorIterator::CHILD_FIRST
  60. );
  61. foreach ($cacheIterator as $cacheFile) {
  62. if (in_array($cacheFile->getBasename(), array('.', '..')))
  63. continue;
  64. elseif ($cacheFile->isFile()) {
  65. if( filemtime($cacheFile->getPathname()) < $cacheTimeLimit )
  66. unlink( $cacheFile->getPathname() );
  67. }
  68. }
  69. }
  70. }
  71. }