isLocked($cacheFile)); if ($this->isLocked($cacheFile)) { // 5 seconds passed, assume the owning process died off and remove it $this->removeLock($cacheFile); } } private function getCacheDir($hash) { // use the first 2 characters of the hash as a directory prefix // this should prevent slowdowns due to huge directory listings // and thus give some basic amount of scalability return Config::get('cache_root') . '/' . substr($hash, 0, 2); } private function getCacheFile($hash) { return $this->getCacheDir($hash) . '/' . $hash; } public function get($key, $expiration = false) { if (! $expiration) { // if no expiration time was given, fall back on the global config $expiration = Config::get('cache_time'); } $cacheFile = $this->getCacheFile($key); // See if this cache file is locked, if so we wait upto 5 seconds for the lock owning process to // complete it's work. If the lock is not released within that time frame, it's cleaned up. // This should give us a fair amount of 'Cache Stampeding' protection if ($this->isLocked($cacheFile)) { $this->waitForLock($cacheFile); } if (File::exists($cacheFile) && File::readable($cacheFile)) { $now = time(); if (($mtime = @filemtime($cacheFile)) !== false && ($now - $mtime) < $expiration) { if (($data = @file_get_contents($cacheFile)) !== false) { $data = unserialize($data); return $data; } } } return false; } public function set($key, $value) { $cacheDir = $this->getCacheDir($key); $cacheFile = $this->getCacheFile($key); if ($this->isLocked($cacheFile)) { // some other process is writing to this file too, wait until it's done to prevent hickups $this->waitForLock($cacheFile); } if (! is_dir($cacheDir)) { if (! @mkdir($cacheDir, 0755, true)) { throw new CacheException("Could not create cache directory"); } } // we serialize the whole request object, since we don't only want the // responseContent but also the postBody used, headers, size, etc $data = serialize($value); $this->createLock($cacheFile); if (! @file_put_contents($cacheFile, $data)) { $this->removeLock($cacheFile); throw new CacheException("Could not store data in cache file"); } $this->removeLock($cacheFile); } public function delete($key) { $file = $this->getCacheFile($key); if (! @unlink($file)) { throw new CacheException("Cache file could not be deleted"); } } }