Cacheoutput : first version : easy method to cache the HTML pages

git-svn-id: https://svn.fournier38.fr/svn/ProgSVN/trunk@1567 bf3deb0d-5f1a-0410-827f-c0cc1f45334c
This commit is contained in:
2014-07-27 06:12:42 +00:00
parent e52cda1216
commit 9d3e7c987f

62
cacheoutput.php Normal file
View File

@@ -0,0 +1,62 @@
<?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 */
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 (3600s 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 (_("Unkwnown cache method : "), $method),
500);
$this->id = $id;
$this->ttl = $ttl;
$this->cacheCWD = getcwd();
$cachemethod = "cache$method";
$this->cache = new $cachemethod ();
$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 datas are sent automatically
}
/** End of saving the datas 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 datas
$datas = array ("content"=>ob_get_contents (),
"headers"=>headers_list ());
$this->cache->write ($this->id, $datas, $this->ttl);
}
}
}