This article describes the PHP file cache content save format, for PHP project development is very practical value. Share for everyone for reference. The specific analysis is as follows:
1, PHP file cache content Save format
PHP file cache Content save format mainly has three kinds:
(1) Variable var_export format into PHP normal assignment writing format;
(2) The variable is serialize after serialization and then deserialized when used;
(3) The variable Json_encode after the format of the save, when used Json_decode
The results of the test on the Internet are: Serialize format of the file parsing efficiency is greater than the Json,json resolution efficiency is greater than the normal PHP assignment.
So if we cache the data, it is quicker to suggest that the data be serialized to parse it.
2, PHP file cache simple case
<?php class Cache_driver {//defines the cached path protected $_cache_path; Gets the path information public function Cache_driver ($config) {if (Is_array ($config) && isset ($CONFI, based on the Cache_path value in $config)
g[' Cache_path ']) {$this->_cache_path = $config [' Cache_path ']; else {$this->_cache_path = Realpath (dirname (__file__). "/") .
"/cache/"; }//Determine whether the file for the key value exists, and if so, read the value value to serialize the store public function get ($id) {if!file_exists ($this->_cache_pat H.
$id)) {return FALSE;
} $data = @file_get_contents ($this->_cache_path. $id);
$data = Unserialize ($data);
if (!is_array ($data) | |!isset ($data [' time ']) | | |!isset ($data [' TTL '])} {return FALSE; } if ($data [' ttl '] > 0 && time () > $data [' time '] + $data [' ttl ']) {@unlink ($this->_cache_path.
$ID);
return FALSE;
return $data [' data '];
//Set cache information, according to key value, generate the corresponding cache file Public function set ($id, $data, $ttl =) {$contents = array ( ' Time ' => time (), ' TTL ' => $ttl, ' data ' => $data); if (@file_put_contents ($this->_cache_path $id, serialize ($contents))) {@chmod ($this->_cache_path. $id, 077
7);
return TRUE;
return FALSE;
The cache file Public function Delete ($id) {return @unlink ($this->_cache_path. $id) is deleted according to the key value.
The Public Function clean () {$DH = @opendir ($this->_cache_path);
if (! $dh) return FALSE;
while ($file = @readdir ($DH)) {if ($file = = "" | | $file = = "...") continue; $path = $this->_cache_path. "/" .
$file;
if (Is_file ($path)) @unlink ($path);
} @closedir ($DH);
return TRUE;
}
}
I hope that the PHP cache instance described in this article can help us to learn from PHP program development.