This article mainly introduces the PHP file cache content storage format, which is a very useful function in PHP program development. if you need it, refer to the example below to describe the PHP file cache content storage format, it is of practical value for PHP project development. Share it with you for your reference. The specific analysis is as follows:
1. php file cache content storage format
There are three main formats for saving php file cache content:
(1) var_export is formatted as a normal value assignment format in PHP;
(2) the variable serialize is saved after serialization and deserialized when used;
(3) the json_encode variable is formatted and saved. when used, json_decode
On the Internet, the test result is: the file parsing efficiency in serialize format is greater than that in Json format, and the Json parsing efficiency is greater than that in PHP normal assignment.
Therefore, we recommend that you parse the data in serialized form faster if the cached data is used.
2. simple php file cache case
<? Phpclass Cache_Driver {// define the cache path protected $ _ cache_path; // Obtain the path information according to the cache_path value in $ config public function Cache_Driver ($ config) {if (is_array ($ config) & isset ($ config ['cache _ path']) {$ this-> _ cache_path = $ config ['cache _ path'];} else {$ this-> _ cache_path = realpath (dirname (_ FILE __). "/"). "/cache/" ;}/// determine whether the file corresponding to the key value exists. if so, read the value and value to serialize and store public function get ($ id) {if (! File_exists ($ this-> _ cache_path. $ 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'];} // sets the cache information and generates the public function set ($ id, $ data, $ ttl = 60) {$ contents = array ('time' => time (), 'ttl '=> $ ttl, 'data' => $ data ); if (@ file_put_contents ($ this-> _ cache_path. $ id, serialize ($ contents) {@ chmo D ($ this-> _ cache_path. $ id, 0777); return TRUE;} return FALSE;} // delete the cache file public function delete ($ id) based on the key value) {return @ unlink ($ this-> _ cache_path. $ id);} 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 ;}}
We hope that the PHP Cache instance described in this article can help you develop PHP programs.