PHP Cache file cache
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
[Php]View plain copy print?
- Class Cache_Driver {
- // Define the cache path
- Protected $ _ cache_path;
- // Obtain the path information based on 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 yes, read the value and value for serialized storage.
- 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'];
- }
- // Set the cache information and generate the corresponding cache file based on the key value
- 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 )))
- {
- @ Chmod ($ this-> _ cache_path. $ id, 0777 );
- Return TRUE;
- }
- Return FALSE;
- }
- // Delete the cached file based on the key value
- Public function delete ($ id)
- {
- 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;
- }
- }