Location: PHPKode > projects > Mocovie web framework > mocovi/library/Cache.php
<?php
/**
 *
 * PHP version 5
 * @copyright	Kai Dorschner 2011
 * @author		Kai Dorschner <hide@address.com>
 * @package		Cache
 * @filesource
 */

/**
 *
 * @author		Kai Dorschner <hide@address.com>
 * @package		ReadVA
 * @subpackage	Filter
 *
 * @todo		implement caching. (memcache?)
 */
class Cache
{
	const DEFAULT_CACHE_PATH = 'cache/';
	protected $cachePath;
	protected $expires = 60;

	public function __construct(DirectoryIterator $path = null)
	{
		if($path)
			$this->cachePath($path);
		else
		{
			if(!is_dir(self::DEFAULT_CACHE_PATH))
				mkdir(self::DEFAULT_CACHE_PATH);
			$this->cachePath(new DirectoryIterator(self::DEFAULT_CACHE_PATH));
		}
	}

	public function cleanup($path = null)
	{
		$path = rtrim($path ? $path : $this->cachePath->getPath(), '/').'/';
		$handle = opendir($path);
		while($element = readdir($handle))
			if($element[0] != '.')
				if(is_dir($path.$element))
				{
					$this->cleanup($path.$element);
					rmdir($path.$element);
				}
				elseif($this->isOld($path.$element))
					unlink($path.$element);
		closedir($handle);
	}

	public function expires($expires = null)
	{
		if(is_null($expires))
			return $this->expires;
		return $this;
	}

	public function value($key, $value = null)
	{
		$path = $this->cachePath->getPath().'/'.$key;
		// get cached value
		if(is_null($value))
		{
			if(file_exists($path) && !$this->isOld($path)) // if is cached
			{
				$this->cacheHeader();
				return file_get_contents($path);
				// return Image::fromFile($path)->text('cached', 'ffffff', 10, 10)->png(); // Debug: Shows "cached" as label on the image
			}
			else // if not cached (anymore)
				return null;
		}
		else
		{
			$this->cacheHeader();
			$this->cacheFile($path, $value);
			return $value;
		}
	}

	public function cachePath(DirectoryIterator $path = null)
	{
		if(is_null($path))
			return $this->cachePath;
		$this->cachePath = $path;
	}

	protected function cacheFile($path, $contents)
	{
		$pathinfo = pathinfo($path);
		if(!is_dir($pathinfo['dirname']))
			mkdir($pathinfo['dirname'], 0777, true);
		file_put_contents($path, $contents);
	}

	protected function isOld($path)
	{
		return ((filectime($path) + $this->expires) <= time());
	}

	protected function cacheHeader()
	{
		header("Pragma: public");
		header("Cache-Control: maxage=".$this->expires);
		header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $this->expires) . ' GMT');
	}
}
Return current item: Mocovie web framework