*/ class SafeCache { private $file; private $sleepDelay; private $spinLimit; public function __construct($file, $sleepDelay = 1000, $spinLimit = 1000) { $this->file = $file; $this->sleepDelay = $sleepDelay; $this->spinLimit = $spinLimit; } public function get() { $handle = @fopen($this->file, 'r'); if($handle === false || !$this->acquireLock($handle, LOCK_SH)) return false; $data = $this->getFileContents($handle); $this->releaseLock($handle); fclose($handle); return $data; } public function save($data) { $handle = @fopen($this->file, 'a'); if($handle === false || !$this->acquireLock($handle, LOCK_EX)) return false; ftruncate($handle, 0); fwrite($handle, $data); $this->releaseLock($handle); fclose($handle); return true; } private function acquireLock($handle, $type) { $hasLock = false; $counter = 0; while(!$hasLock) { $hasLock = flock($handle, $type + LOCK_NB); if($counter++ > $this->spinLimit) { fclose($handle); return false; } usleep($this->sleepDelay); } return true; } private function releaseLock($handle) { flock($handle, LOCK_UN); } private function getFileContents($handle) { $data = ''; while (!feof($handle)) { $data .= fread($handle, 8192); } return $data; } } ?>