[FileCache] Add property to define cache folder

This commit is contained in:
logmanoriginal 2016-10-08 16:03:08 +02:00
parent 5639b158e7
commit 2d56b717cf
2 changed files with 30 additions and 9 deletions

View file

@ -4,6 +4,7 @@
*/ */
class FileCache implements CacheInterface { class FileCache implements CacheInterface {
protected $path;
protected $param; protected $param;
public function loadData(){ public function loadData(){
@ -32,7 +33,7 @@ class FileCache implements CacheInterface {
public function purgeCache(){ public function purgeCache(){
$cacheTimeLimit = time() - 86400; // 86400 -> 24h $cacheTimeLimit = time() - 86400; // 86400 -> 24h
$cachePath = $this->getCachePath(); $cachePath = $this->getPath();
if(file_exists($cachePath)){ if(file_exists($cachePath)){
$cacheIterator = new RecursiveIteratorIterator( $cacheIterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($cachePath), new RecursiveDirectoryIterator($cachePath),
@ -50,6 +51,28 @@ class FileCache implements CacheInterface {
} }
} }
/**
* Set cache path
* @return self
*/
public function setPath($path){
if(is_null($path) || !is_string($path)){
throw new \Exception('The given path is invalid!');
}
$this->path = $path;
// Make sure path ends with '/' or '\'
$lastchar = substr($this->path, -1, 1);
if($lastchar !== '/' && $lastchar !== '\\')
$this->path .= '/';
if(!is_dir($this->path))
mkdir($this->path, 0755, true);
return $this;
}
/** /**
* Set HTTP GET parameters * Set HTTP GET parameters
* @return self * @return self
@ -64,15 +87,12 @@ class FileCache implements CacheInterface {
* Return cache path (and create if not exist) * Return cache path (and create if not exist)
* @return string Cache path * @return string Cache path
*/ */
protected function getCachePath(){ protected function getPath(){
$cacheDir = __DIR__ . '/../cache/'; // FIXME : configuration ? if(is_null($this->path)){
throw new \Exception('Call "setPath" first!');
if(!is_dir($cacheDir)){
mkdir($cacheDir, 0755, true);
chmod($cacheDir, 0755);
} }
return $cacheDir; return $this->path;
} }
/** /**
@ -80,7 +100,7 @@ class FileCache implements CacheInterface {
* @return string Path to the file cache * @return string Path to the file cache
*/ */
protected function getCacheFile(){ protected function getCacheFile(){
return $this->getCachePath() . $this->getCacheName(); return $this->getPath() . $this->getCacheName();
} }
/** /**

View file

@ -130,6 +130,7 @@ try {
// Initialize cache // Initialize cache
$cache = Cache::create('FileCache'); $cache = Cache::create('FileCache');
$cache->setPath(__DIR__ . '/cache');
$cache->purgeCache(); $cache->purgeCache();
$cache->setParameters($params); $cache->setParameters($params);