Files
DomFramework/cacheoutput.php
2016-02-21 19:21:29 +00:00

69 lines
2.0 KiB
PHP

<?php
/** This class permit to cache the ouptut of a code. If the cache is already
available, use it.
It resend the headers as the ouptut send them
Use it by :
$c = new cacheoutput ("URL");
Don't forget to define a variable or the cache saved is always empty */
class cacheoutput
{
/** Record if the saving of pages is on going */
private $saving = false;
/** The called id */
private $id = null;
/** The called ttl */
private $ttl = null;
/** The cache object */
private $cache = null;
/** Current path at start due to lack of information in __destruct*/
private $cacheCWD = null;
/**
@param string $id The cache identifier
@param integer|null $ttl The cache Time to Leave in seconds (60s by
default)
@param string|null $method The cache method to use */
public function __construct ($id, $ttl=60, $method="file")
{
$res = @include ("domframework/cache$method.php");
if ($res === false)
throw new Exception (sprintf (dgettext("domframework",
"Unkwnown cache method : "), $method),
500);
$this->id = $id;
$this->ttl = $ttl;
$this->cacheCWD = getcwd();
$cachemethod = "cache$method";
$this->cache = new $cachemethod ();
if ($ttl === 0)
$this->cache->nocache = 1;
$res = $this->cache->read ($id);
// If there is a cache : display it
if ($res !== false)
{
foreach ($res["headers"] as $header)
@header ($header);
echo $res["content"];
exit;
}
ob_start ();
$this->saving = true;
// The data are sent automatically
}
/** End of saving the data in cache */
public function __destruct ()
{
// Force the path because it return to / in the destructor
chdir ($this->cacheCWD);
if ($this->saving === true)
{
// Do the saving of the data
$data = array ("content"=>ob_get_contents (),
"headers"=>headers_list ());
$this->cache->write ($this->id, $data, $this->ttl);
}
}
}