1, PHP file cache content Save format
PHP file cache Content storage format is mainly three kinds:
(1) Variable var_export formatted into PHP normal assignment writing format;
(2) The variable serialize is stored after serialization and is deserialized when used;
(3) The variable json_encode is saved after formatting, when used Json_decode
The test results on the Internet are as follows: The parsing efficiency of serialize format is greater than that of Json,json, which is higher than php normal assignment.
So if we cache the data, we suggest that parsing the data in serialized form is faster.
2. Simple case of PHP file cache
[PHP]View Plaincopyprint?
- <?php
- class cache_driver{
- //Define the path of the cache
- protected $_cache_path;
- //Get path information based on 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 if the file corresponding to the key value exists, and if present, read value, value to serialize the 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, generate the corresponding cache file according to the key value
- 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 , 0777);
- return TRUE;
- }
- return FALSE;
- }
- //Delete the cache file according to the key value
- Public functiondelete($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;
- }
- }
PHP Cache File Cache