Home > PHP > Class Cache

Class Cache

December 17, 2009

Notice: This class is not for public usage and is subject to change.


<?php
/**
 * Class Cache. A caching class. Requires PHP 5+
 *
 * @package    		Cache
 * @category   		Caching
 * @author     		Costin Trifan 
 * @copyright  		2009 Costin Trifan
 * @licence    		Attribution-NonCommercial-NoDerivs 2.5	http://creativecommons.org/licenses/by-nc-nd/2.5/legalcode
 * @version    		1.0
 * @last-update		dec.2009
 *
 * THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE").
 * THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS
 * LICENSE OR COPYRIGHT LAW IS PROHIBITED.
 * 
 * BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE.
 * THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. 
 *
 *	http://creativecommons.org/licenses/by-nc-nd/2.5/legalcode
 */
class Cache
{

	private function __clone(){}
	private function __sleep(){}
	private function __wakeup(){}

	public function __get( $name ) { return null; }
	public function __set( $name, $value ) { }


# PROTECTED PROPERTIES
#======================

	protected
		 $_cacheDir = "cache/"
		,$_cacheLifetime = 3600
		;

	private $_cacheFileExt = '.php';



# PUBLIC METHODS
#======================

	public function __construct( $cacheDir, $createCacheDir = false, $cacheLifetime = 3600 )
	{
		if ( ! is_dir($cacheDir) )
		{
			if ($createCacheDir) {
				mkdir($cacheDir, 0775);
			}
			else exit('The cache directory was not found!');
		}
		if ( is_writable($cacheDir) ) {
			$this->SetCacheDir($cacheDir);
		}
		else { exit("The cache directory '$cacheDir' is not writable! Check permissions."); }

		$this->SetCacheLifetime($cacheLifetime);
	}


	public function Cache( $file )
	{
		$savefilepath = $this->_setFilePath($file);

		if ( ! file_exists($file)) { return $this; }

/*
 *	TODO:
 *
 * :: execute php code inside templates
---------------------------------------
		$data = '';
		ob_start();
			include_once $file;
			$data = ob_get_contents();
		ob_end_clean();


*/
		$data = file_get_contents($file, false);
		$data = htmlentities($data, ENT_QUOTES);
		file_put_contents($savefilepath, $data);
		return $this;
	}


	public function CacheBlock( $file, $content )
	{
		$savefilepath = $this->_setFilePath($file);

		if ( ! file_exists($file)) { return $this; }

		$data = htmlentities($content, ENT_QUOTES);
		file_put_contents($savefilepath, $data);

		return $this;
	}


	public function Get( $file )
	{
		$fpath = $this->_setFilePath($file);

		$data = '';

		if ( $this->_isCached($fpath) )
		{
			$data = file_get_contents($fpath);
			$data = html_entity_decode($data, ENT_QUOTES);
		}
		return $data;
	}


	/**
	 * Att! Not to be used internally!
	 * Use the private _IsCached($file) instead!!
	 */
	public function IsCached( $file )
	{
		return $this->_IsCached($this->_setFilePath($file));
	}


	/**
	* Delete all files from the cache directory.
	*
	* return $this
	*/
	public function EmptyDirectory()
	{
		$files = $this->_getCachedFiles();
		if (count($files) > 0) {
			foreach ($files as $file)
				unlink($file);
		}
		return $this;
	}

	/**
	* Delete a cached template.
	*
	* param string $fileNames  The name(s) of the file(s) to delete.
	* return $this
	*/
	public function Delete(/* [ $fileName, $fileName,...] */)
	{
		$files = func_get_args();
		if (count($files) > 1) {
			foreach ($files as $file) {
				$_file = $this->_setFilePath($file);
				if (file_exists($_file)) {
					unlink($_file);
				}
			}
		}
		return $this;
	}



	public function SetCacheDir( $dir )
	{
		$this->_cacheDir = $dir;
                return $this;
	}

	public function GetCacheDir()
	{
		return $this->_cacheDir;
	}

	public function SetCacheLifetime( $seconds )
	{
		if (is_numeric($seconds)) {
			$this->_cacheLifetime = $seconds;
		}
		return $this;
	}

	public function GetCacheLifetime()
	{
		return $this->_cacheLifetime;
	}






# PRIVATE METHODS
#======================

	private function _encodeName( $file )
	{
		return md5(basename($file));
	}


	private function _setFilePath( $file )
	{
		$file = $this->_cacheDir.$this->_encodeName($file).$this->_cacheFileExt;
		return $file;
	}


	private function _isCached( $file )
	{
		$_cached = false;

		if (file_exists($file)) /*[ requires $file to be encoded !! ]*/
		{
			clearstatcache();

			if (filemtime($file) > (time() - $this->_cacheLifetime)) {
				$_cached = true;
			}
		}
		return $_cached;
	}


	/**
	* Get all files from the cache directory.
	* access protected
	* return array
	*/
	private function _getCachedFiles()
	{
		$fileList = array();
		$fileCount = 0;

		if ($dir = opendir($this->_cacheDir))
		{
			while ($file = readdir($dir))
			{
				if ($file != '.' && $file != '..')
				{
					$finfo = pathinfo($file);
					$fext = '.' . $finfo['extension'];

					if (strcasecmp($fext, $this->_cacheFileExt) == 0)
					{
						array_push($fileList, $file);
						$fileCount++;
					}
				}
			}
			closedir($dir);
		}
		return $fileList;
	}


}
/*[ end class ]*/
?>
Advertisements
Categories: PHP Tags: ,
  1. No comments yet.
  1. December 24, 2009 at 8:09 am
Comments are closed.
%d bloggers like this: