phpファイルキャッシュクラス


<?php
/**
 *      
 * @author flynetcn
 */
class FileCache
{
	const CACHE_DIR = '/tmp/cache';
	private $dir;
	private $expire = 300;

	/**
	 * @param $strDir      (   cache)
	 */
	function __construct($strDir='')
	{
		if ($strDir) {
			$this->dir = self::CACHE_DIR.'/'.$strDir;
		}
	}

	private function getFileName($strKey)
	{
		return $this->dir.'/'.$strKey;
	}

	public function setExpire($intSecondNum)
	{
		if ($intSecondNum<10 || !is_int($intSecondNum)) {
			return false;
		}
		$this->expire = $intSecondNum;
		return true;
	}

	public function getExpire()
	{
		return $this->expire;
	}

	public function get($strKey)
	{
		$strFileName = $this->getFileName($strKey);
		if (!@file_exists($strFileName)) {
			return false;
		}
		if (filemtime($strFileName) < (time()-$this->expire)) {
			return false;
		}
		$intFileSize = filesize($strFileName);
		if ($intFileSize == 0) {
			return false;
		}
		if (!$fp = @fopen($strFileName, 'rb')) {
			return false;
		}
		flock($fp, LOCK_SH);
		$cacheData = unserialize(fread($fp, $intFileSize));
		flock($fp, LOCK_UN);
		fclose($fp);
		return $cacheData;
	}

	public function set($strKey, $cacheData)
	{
		if (!is_dir($this->dir)) {
			if (!@mkdir($this->dir, 0755, true)) {
				trigger_error("mkdir({$this->dir}, 0755, true) failed", E_USER_ERROR);
				return false;
			}
		}
		$strFileName = $this->getFileName($strKey);
		if (@file_exists($strFileName)) {
			$intMtime = filemtime($strFileName);
		} else {
			$intMtime = 0;
		}
		if (!$fp = fopen($strFileName,'wb')) {
			return false;
		}
		if (!flock($fp, LOCK_EX+LOCK_NB)) {
			fclose($fp);
			return false;
		}
		if (time() - $intMtime < 1) {
			flock($fp, LOCK_UN);
			fclose($fp);
			return false;
		}
		fseek($fp, 0);
		ftruncate($fp, 0);
		fwrite($fp, serialize($cacheData));
		flock($fp, LOCK_UN);
		fclose($fp);
		@chmod($strFileName, 0755);
		return true;
	}
}