Php abstract cache class & lt ;? Phprequire_oncedirname (_ FILE _)... ModelIfaceIcache. php; other {static & nbsp; $ cache_dir; const & nbsp; CACHETIME6 php abstract cache class
Require_once dirname (_ FILE _). "/../Model/Iface/Icache. php ";
Abstract class AllCache implements Icache
{
Static $ cache_dir;
Const CACHETIME = 60; // The cache time is 60 seconds.
Static $ _ data;
Static $ _ interce;
// Constructor
Public function _ construct ()
{
$ Cache_dirname = dirname (_ FILE _). "/../Cache ";
If ([email protected] _ dir ($ cache_dirname ))
{
If ([email protected] ($ cache_dirname, 0777 ))
{
Self: msgbox ('The cached file does not exist and cannot be created, you need to manually create .');
Return false;
}
}
Self: $ cache_dir = $ cache_dirname;
}
/**
* Static call
* Self indicates the class itself.
*/
Public static function getInstance ()
{
If (! (Self: $ _ interce instanceof self )){
Self: $ _ interce = new self ();
}
Return self: $ _ interce;
}
// Output exception
Private function msgbox ($ errorstring)
{
Echo"
Error:".$errorstring."
";
}
// Set the cache file
Private function cache_page ($ pageurl, $ pagedata)
{
If (! $ Fso = fopen ($ pageurl, 'w ')){
Self: msgboxs ('cache file cannot be opened. '); // trigger_error
Return false;
}
If (! Flock ($ fso, LOCK_EX) {// LOCK_NB, locking
Self: msgboxs ('unable to lock the cache file. '); // trigger_error
Return false;
}
If (! Fwrite ($ fso, $ pagedata) {// write byte stream, serialize writes to other formats
Self: msgboxs ('cache file cannot be written. '); // trigger_error
Return false;
}
Flock ($ fso, LOCK_UN); // release lock
Fclose ($ fso );
Return true;
}
// Read the file status
Private function isOpenCache ($ cacheFile)
{
If (! File_exists ($ cacheFile )){
Self: msgbox ('cache file cannot be read. '); exit;
}
/* Echo 'read the cached file: '. $ cacheFile;
Return unserialize (file_get_contents ($ cacheFile ));
$ Fso = fopen ($ cacheFile, 'r ');
$ Data = fread ($ fso, filesize ($ cacheFile ));
Fclose ($ fso );
Return $ data ;*/
}
/**
* Format data
*/
Private function setFileContent ($ data)
{
$ Html =" $ Html. = "\ $ data =". var_export ($ data, true). "; \ n ";
$ Html. = "?> ";
Return $ html;
}
/**
* Set cache data
* @ Param $ cacheFile cache file name
× @ Param $ _ data cache data source
*/
Public function readdata($cachefile='ulult_cache.txt ', $ _ data)
{
$ _ Data = self: SetFileContent ($ _ data );
$ CacheFile = self: $ cache_dir. "/". $ cacheFile;
If (file_exists ($ cacheFile ))
{
Self: isOpenCache ($ cacheFile );
If (filemtime ($ cacheFile) <(time ()-self: CACHETIME ))
{
Self: cache_page ($ cacheFile, $ _ data );
}
} Else {
Self: cache_page ($ cacheFile, $ _ data );
}
Require_once ($ cacheFile );
Self: $ _ data = $ data;
}
/**
* Getting data
*/
Public function GetData ()
{
Return self: $ _ data;
}
}
/*
AllCache: readData ("cache_news.php", array (0, 1, 2, 3, 5, 6 ));
Print_r (AllCache: GetData ());
*/
?>