The example in this article describes the PHP file cache content saving format, which is of great practical value for PHP project development. Share it with everyone for your reference. The specific analysis is as follows:
1. PHP file cache content saving format
There are three main formats for saving PHP file cache content:
(1) The variable var_export is formatted into PHP’s normal assignment writing format;
(2) The variable serialize is saved after serialization and deserialized when used;
(3) The variable json_encode is formatted and saved. When used, json_decode
The test results on the Internet are: the file parsing efficiency of serialize format is greater than Json, and the parsing efficiency of Json is greater than PHP normal assignment.
Therefore, if we cache data, it is recommended to use serialization to parse the data faster.
2. Simple case of PHP file caching
<?php class Cache_Driver { //定义缓存的路径 protected $_cache_path; //根据$config中的cache_path值获取路径信息 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/"; } } //判断key值对应的文件是否存在,如果存在,读取value值,value以序列化存储 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']; } //设置缓存信息,根据key值,生成相应的缓存文件 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; } //根据key值,删除缓存文件 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; } }
We hope that the PHP caching examples described in this article can be of help and reference to everyone's PHP program development.