A simple PHP Cache code is extremely simple. There is a lot of information about the PHP Cache class on the Internet, but this class should be a simple one that I have seen to meet the requirements. Let's just look at the code! Instructions for Use: there is a lot of information about the PHP Cache class on the Internet, but this class should be a simple one that I have seen to meet the requirements. Let's just look at the code!
Instructions for use:
1. instantiation
$ Cache = new Cache ();
2. set cache time and cache Directory
$ Cache = new Cache (60, '/any_other_path /');
The first parameter is the cache seconds, and the second parameter is the cache path, which can be configured as needed.
By default, the cache duration is 3600 seconds, and the cache directory is cache/
3. read cache
$ Value = $ cache-> get ('data _ key ');
4. write cache
$ Value = $ cache-> put ('data _ key', 'data _ value ');
Complete instance:
$ Cache = new Cache ();
// Read key value $ key data from the cache
$ Values = $ cache-> get ($ key );
// If no data is cached
If ($ values = false ){
// Insert code here...
// Write data with the key value $ key
$ Cache-> put ($ key, $ values );
} Else {
// Insert code here...
}
Cache. class. php
Class Cache {
Private $ cache_path; // path for the cache
Private $ cache_expire; // seconds that the cache expires
// Cache constructor, optional expiring time and cache path
Public function Cache ($ exp_time = 3600, $ path = "cache /"){
$ This-> cache_expire = $ exp_time;
$ This-> cache_path = $ path;
}
// Returns the filename for the cache
Private function fileName ($ key ){
Return $ this-> cache_path.md5 ($ key );
}
// Creates new cache files with the given data, $ key = name of the cache, data the info/values to store
Public function put ($ key, $ data ){
$ Values = serialize ($ data );
$ Filename = $ this-> fileName ($ key );
$ File = fopen ($ filename, 'w ');
If ($ file) {// able to create the file
Fwrite ($ file, $ values );
Fclose ($ file );
}
Else return false;
}
// Returns cache for the given key
Public function get ($ key ){
$ Filename = $ this-> fileName ($ key );
If (! File_exists ($ filename) |! Is_readable ($ filename) {// can't read the cache
Return false;
}
If (time () <(filemtime ($ filename) + $ this-> cache_expire) {// cache for the key not expired
$ File = fopen ($ filename, "r"); // read data file
If ($ file) {// able to open the file
$ Data = fread ($ file, filesize ($ filename ));
Fclose ($ file );
Return unserialize ($ data); // return the values
}
Else return false;
}
Else return false; // was expired you need to create new
}
}
?>
From: http://www.mangguo.org/
There is a lot of information about the caching PHP class, but this class should be a simple one that I have seen to meet the requirements of the function. Let's just look at the code! Instructions for Use :...