2007-07-09 00:38:32 +04:00
|
|
|
<?php
|
|
|
|
|
|
|
|
class Cache
|
|
|
|
{
|
|
|
|
protected $_dir;
|
|
|
|
protected $_ext;
|
|
|
|
protected $_page;
|
|
|
|
protected $_file;
|
|
|
|
|
2007-07-09 13:24:05 +04:00
|
|
|
public function __construct($dir, $ext)
|
2007-07-09 00:38:32 +04:00
|
|
|
{
|
|
|
|
$this->_dir = $dir;
|
|
|
|
$this->_ext = $ext;
|
|
|
|
|
|
|
|
$this->_page = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
|
|
|
|
$this->_file = $this->_dir . md5($this->_page) . '.' . $this->_ext;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Begins caching the output.
|
|
|
|
*
|
|
|
|
* @return A boolean value indicating whether a valid cached version of the
|
|
|
|
* page was found and echoed (false), or not (true).
|
|
|
|
*/
|
|
|
|
public function begin()
|
|
|
|
{
|
|
|
|
$showCache = (file_exists($this->_file) && $this->isValid());
|
|
|
|
clearstatcache();
|
|
|
|
|
|
|
|
if ($showCache) {
|
|
|
|
readfile($this->_file);
|
|
|
|
return false;
|
|
|
|
} else {
|
|
|
|
ob_start();
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Ends caching the output and saves it to a cache file.
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
public function end()
|
|
|
|
{
|
|
|
|
// Generate a new cache file
|
|
|
|
$fp = @fopen($this->_file, 'w');
|
|
|
|
|
|
|
|
// Save the contents of output buffer to the file
|
|
|
|
@fwrite($fp, ob_get_contents());
|
|
|
|
@fclose($fp);
|
|
|
|
|
|
|
|
ob_end_flush();
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Deletes all files in the cache directory.
|
|
|
|
*/
|
|
|
|
public function clear()
|
|
|
|
{
|
2007-07-20 12:03:04 +04:00
|
|
|
if ($handle = @opendir($this->_dir)) {
|
2007-07-09 00:38:32 +04:00
|
|
|
while ($file = readdir($handle)) {
|
|
|
|
if ($file !== '.' && $file !== '..') {
|
2007-07-09 13:24:05 +04:00
|
|
|
@unlink($this->_dir . '/' . $file);
|
2007-07-09 00:38:32 +04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
closedir($handle);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* This method is used to check whether the cache file is valid to use.
|
|
|
|
*
|
2007-07-09 13:24:05 +04:00
|
|
|
* Currently it assumes that the cache file is always valid.
|
2007-07-09 00:38:32 +04:00
|
|
|
*
|
|
|
|
* @return True, if cache file is valid; false otherwise.
|
|
|
|
*/
|
|
|
|
protected function isValid()
|
|
|
|
{
|
2007-07-09 13:24:05 +04:00
|
|
|
return true;
|
2007-07-09 00:38:32 +04:00
|
|
|
}
|
|
|
|
}
|