The example in this article describes the file caching class of PHP. Share it with everyone for your reference. The specific analysis is as follows:
Cache class is a commonly used function when we develop applications. Let’s sort out several PHP file cache classes for you. Each file cache class is written differently, but there will be differences in performance. Those who are interested in testing it Friends can test these cache classes.
Example 1
Copy code The code is as follows:
$fzz = new fzz_cache;
$fzz->kk = $_SERVER; //Write cache
//$fzz->set("kk",$_SERVER,10000); //This method does not conflict with class attributes, and any cache name can be used;
print_r($fzz->kk); //Read cache
//print_r($fzz->get("kk"));
//unset($fzz->kk); //Delete cache
//$fzz->_unset("kk");
var_dump(isset($fzz->kk)); //Determine whether the cache exists
//$fzz->_isset("kk");
//$fzz->clear(); //Clear expired cache
//$fzz->clear_all(); //Clear all cache files
class fzz_cache{
public $limit_time = 20000; //Cache expiration time
public $cache_dir = "data"; //Cache file storage directory
//Write cache
function __set($key, $val){
$this->_set($key ,$val);
}
//The third parameter is the expiration time
function _set($key,$val,$limit_time=null){
$limit_time = $limit_time ? $limit_time : $this->limit_time;
$file = $this->cache_dir."/".$key.".cache";
$val = serialize($val);
@file_put_contents($file,$val) or $this->error(__line__,"fail to write in file");
@chmod($file,0777);
@touch($file,time()+$limit_time) or $this->error(__line__,"fail to change time");
}
//Read cache
function __get($key){
Return $this->_get($key);
}
function _get($key){
$file = $this->cache_dir."/".$key.".cache";
if (@filemtime($file)>=time()){
Return unserialize(file_get_contents($file));
}else{
@unlink($file) or $this->error(__line__,"fail to unlink");
Return false;
}
}
//Delete cache files
function __unset($key){
Return $this->_unset($key);
}
function _unset($key){
if (@unlink($this->cache_dir."/".$key.".cache")){
Return true;
}else{
Return false;
}
}
//Check whether the cache exists, if it expires, it is considered not to exist
function __isset($key){
return $this->_isset($key);
}
function _isset($key){
$file = $this->cache_dir."/".$key.".cache";
if (@filemtime($file)>=time()){
Return true;
}else{
@unlink($file) ;
Return false;
}
}
//Clear expired cache files
function clear(){
$files = scandir($this->cache_dir);
foreach ($files as $val){
if (filemtime($this->cache_dir."/".$val)
@unlink($this->cache_dir."/".$val);
}
}
}
//Clear all cache files
function clear_all(){
$files = scandir($this->cache_dir);
foreach ($files as $val){
@unlink($this->cache_dir."/".$val);
}
}
function error($msg,$debug = false) {
$err = new Exception($msg);
$str = "
Example 2. PHP file cache class extracted from CI community's stblog and CI's file_helper class, a simple file-based key->value cache class.
This class can be used to cache some basic information, such as some infrequent changes in the header, footer, and sidebar of the blog, and the content taken out from the database. Before fetching the data, first determine whether the content in the file cache has expired. If not, Take it out when it expires. If it expires, connect to the database to query, rewrite the results into the file cache, and update the expiration time. It is similar to using memcache, but more convenient. It is enough for some small applications.
The specific code is as follows
Copy code The code is as follows:
define('DIRECTORY_SEPARATOR','/');
define('FOPEN_WRITE_CREATE_DESTRUCTIVE','wb');
define('FOPEN_WRITE_CREATE','ab');
define('DIR_WRITE_MODE', 0777);
class FileCache {
/**
* Cache path
*
* @access private
* @var string
*/
private $_cache_path;
/**
* Cache expiration time, unit is second
*
* @access private
* @var int
*/
private $_cache_expire;
/**
* Parse function, set cache expiration practice and storage path
* *
* @access public
* @return void
*/
public function __construct($expire, $cache_path)
{
$this->_cache_expire = $expire;
$this->_cache_path = $cache_path;
}
/**
* Cache file name
* *
* @access public
* @param string $key
* @return void
*/
private function _file($key)
{
return $this->_cache_path . md5($key);
}
/**
* * Set cache
* *
* @access public
* @param string $key The unique key of the cache
* @param string $data cached content
* @return bool
*/
public function set($key, $data)
{
$value = serialize($data);
$file = $this->_file($key);
return $this->write_file($file, $value);
}
/**
* Get cache
* *
* @access public
* @param string $key The unique key of the cache
* @return mixed
*/
public function get($key)
{
$file = $this->_file($key);
/**File does not exist or directory is not writable*/
if (!file_exists($file) || !$this->is_really_writable($file))
{
return false;
}
/**The cache has not expired and is still available*/
if ( time() < (filemtime($file) + $this->_cache_expire) )
{
return TRUE;
}
function is_really_writable($file)//兼容各平台判断文件是否有写入权限
{
// If we're on a Unix server with safe_mode off we call is_writable if (DIRECTORY_SEPARATOR == '/' AND @ini_get("safe_mode") == FALSE)
{
return is_writable($file);
}
// For windows servers and safe_mode "on" installations we'll actually
// write a file then read it. Bah...
if (is_dir($file))
{
$file = rtrim($file, '/').'/'.md5(rand(1,100));
fclose($fp);
return TRUE;
}
}
$cache = new FileCache(30,'cache/');
$cache->set('test','this is a test.');
print $cache->get('test');
/* End of file FlieCache.php */
/**
* Get an instance of this class
*
* @return Ambiguous
*/
public static function getInstance()
{
if(self::$_instance === null)
{
self::$_instance = new self();
}
return self::$_instance;
}
/**
* Get cache information
*
* @param string $id
* @return boolean|array
*/
public static function get($id)
{
$instance = self::getInstance();
/**
* Set up a cache
*
* @param string $id Cache id
* @param array $data cache content
* @param int $cacheLife Cache life Default is 0 unlimited life
*/
public static function set($id, $data, $cacheLife = 0)
{
$instance = self::getInstance();
/**
* Get cache information
*
* @param string $id cache id
* @return string|array cache data
*/
static function load($id)
{
$self = & self::getInstance();
$time = time();
//检测缓存是否存在
if (!$self->test($id)) {
// The cache is not hit !
return false;
}
/**
* Clear a cache
* *
* @param string cache id
* @return void
*/
static function del($id)
{
$self = & self::getInstance();
If(!$self->test($id)){
//The cache does not exist
Return false;
}
$file = $self->_file($id);
Return unlink($file);
}
}
Save data
Copy code The code is as follows:
$config = array(
'name' => 'xiaojiong',
'qq' => '290747680',
'age' => '20',
);
//The first parameter cache data
//Second parameter cache id
//The third parameter cache_life 0 will never expire (except cache::clear() to clear everything). The default cache_life is option_cache_life
cache::save($config,'config',0);
Load data
Copy code The code is as follows:
//Only one parameter cache_id
$config = cache::load('config');
Clear cache
//Clear the specified cache
cache::del('config');
//Clear all caches
cache::clear();
Cache information configuration
//Call before executing all cache_func
$_options = array(
'cache_dir' => './cache', //Cache file directory
'file_name_prefix' => 'cache',//Cache file prefix
'file_life' => 100000, //Cache file life
);
cache::setOptions($options);
//If executed again, it will be executed according to the new configuration information, otherwise it will be the default information
cache::save($arr,'arr');
This method seems unreasonable, and interested friends can improve it. I hope this article will be helpful to everyone’s PHP programming.
http://www.bkjia.com/PHPjc/915434.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/915434.htmlTechArticleA summary of PHP file cache classes. This article describes the PHP file cache class with examples. Share it with everyone for your reference. The specific analysis is as follows: The cache class is commonly used in our development applications...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn