|
<?php
/*************************************
Chiwa Kantawong
http://www.zengcode.com
p@zengcode.com
20 July 2010
*************************************/
header('Content-type: text/html; charset=utf-8');
Class ZengCache
{
public static $cachePath;
public static $cacheTime = 5; //seconds
public static $cacheName;
public static $showLoadTime = false;
public static function StartCache($path,$time=null)
{
if ( ZengCache::$showLoadTime == true )
{
$starttime = explode(' ', microtime());
$starttime = $starttime[1] + $starttime[0];
}
ob_start();
if ($_POST) return;
if ($path == null || $path == "")
die('!! Cache need save path !!');
else
ZengCache::$cachePath = $path;
if ($time != null) ZengCache::$cacheTime = $time;
ZengCache::$cacheName = md5($_SERVER['PHP_SELF']) ;
$cachetime = ZengCache::$cacheTime * 60;
if (file_exists( ZengCache::$cachePath.'\\'.ZengCache::$cacheName) &&
(time() - $cachetime < filemtime( ZengCache::$cachePath.'\\'.ZengCache::$cacheName)))
{
include( ZengCache::$cachePath.'\\'.ZengCache::$cacheName);
echo "\n<!-- From cache generated =>".ZengCache::$cacheName."-->";
//Load time
if ( ZengCache::$showLoadTime == true )
{
$mtime = explode(' ', microtime());
$totaltime = $mtime[0] + $mtime[1] - $starttime;
printf('<br>Page loaded in %.3f seconds.', $totaltime);
}
ob_end_flush();
exit;
}
}//
public static function EndCache()
{
$fp = fopen( ZengCache::$cachePath.'\\'.ZengCache::$cacheName, 'w');
if (flock($fp, LOCK_EX)) {
fwrite($fp, ob_get_contents());
flock($fp, LOCK_UN);
}
fclose($fp);
ob_end_flush();
//Load time
if ( ZengCache::$showLoadTime == true )
{
$mtime = explode(' ', microtime());
$totaltime = $mtime[0] + $mtime[1] - $starttime;
printf('<br>Page loaded in %.3f seconds.', $totaltime);
}
}//
}//
?>
<?php
//use ZengCache
ZengCache::$showLoadTime = true;
ZengCache::StartCache("C:\\ZengCache",1); //param1=path of cache file, param2= expiration time of cache file (minutes) รอ 1 นาทีดู load time ครับจะแตกต่างกัน
//======================ส่วนการทำงาน ปกติ ===============//
for($i=1; $i<=5;$i++)
{
sleep(1); //sleep 1 วินาที สมมิตว่าตรงนี้เป็นส่วนที่ติดต่อ กับ database หรือใช้เวลาคำนวณมากๆ
echo "\n<br> Zeng ครั้งที่ : ".$i;
}
//======================ส่วนการทำงาน ปกติ ===============//
ZengCache::EndCache();
?>
|