There are a lot of information about PHP caching classes on the Web, but this class should be one that I've seen that features meet demand, but that's incredibly simple. Don't say much nonsense, look at the code directly!
Instructions for use:
1, the instantiation of
$cache = new cache ();
2. Set cache time and cache directory
$cache = new Cache ('/any_other_path/');
The first parameter is the number of cached seconds, and the second parameter is the cached path, configured as needed.
By default, the cache time is 3,600 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 ');
Full Example:
$cache = new cache ();
Data from the cache $key reading the key value
$values = $cache->get ($key);
If there is no cached data if
($values = = False) {
//insert code here ...
Data written to the key value $key
$cache->put ($key, $values);
} else {
//insert code here ...
}
Cache.class.php
<?php class Cache {private $cache _path;//path for the cache private $cache _expire;//seconds that cache expires Cache constructor, optional expiring time and cache path Public function cache ($exp _time=3600, $path = "cache/") {$th
Is->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 functi
On 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 your need to create new}}?>
I am sure you will like this concise PHP cache class code, I hope to help you learn.