This article and everyone to share a very simple PHP cache class code, caching applications for the development of PHP project is particularly important, the need for friends to refer to. We hope to help you.
There is a lot of data about PHP cache classes on the Web, but this class should be one of the things I've seen that meets the needs of functionality, but is incredibly concise. Don't say much nonsense, just look at the code!
Instructions for use:
1. Instantiation
$cache = new cache ();
2. Set cache time and cache directory
$cache = new Cache ('/any_other_path/');
The first parameter is the number of seconds to cache, the second parameter is the cache path, and is 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 ');
Complete Example:
$cache = new cache (); Data $key from the cache reading the key value $values = $cache->get ($key); If there is no cached data if ($values = = False) {//insert code here ...//write key value $key data $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 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 CR Eate 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 ($fi Lename) | | !is_readable ($filename)) {//can ' t read the cache return false;} if (Time () < (Filemtime ($filename) + $this->cache_e Xpire) {//cache for the key is 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}}?>
Related recommendations:
How PHP bulk modifies table structure
PHP use Redis queue to implement e-commerce order automatic Confirmation receipt
A detailed explanation of PHP XML file additions and deletions