php粉絲教程小編為各位介紹一篇php 部分緩存數據庫返回數據的例子,這個例子其實是非常的實用了,希望能夠幫助到大家.
- $cache = new FileCache();
- $new_arr = $cache->get('gsmcache');//yourkey是你為每一個要緩存的數據定義的緩存名字
- if ($new_arr===false) {
- $new_arr="數據庫返回的數據";
- $cache->set('gsmcache',$new_arr,3600);//緩存3600秒
- }
- <?php
- /**
- * 文件緩存類
- *
- * @copyright blog.itiwin.cn
- * @author More
- * @package cache
- * @version v0.1
- */
- class FileCache {
- /**
- * @var string $cachePath 緩存文件目錄
- * @access public
- */
- public $cachePath = './';
- /**
- * 構造函數
- * @param string $path 緩存文件目錄
- */
- function __construct($path = NULL) {
- if ($path) {
- $this->cachePath = $path;
- }
- }
- /**
- * 析構函數
- */
- function __destruct() {
- //nothing
- }
- /**
- * 在cache中設置鍵為$key的項的值,如果該項不存在,則新建一個項
- * @param string $key 鍵值
- * @param mix $var 值
- * @param int $expire 到期秒數
- * @param int $flag 標志位
- * @return bool 如果成功則返回 TRUE,失敗則返回 FALSE。
- * @access public
- */
- public function set($key, $var, $expire = 36000, $flag = 0) {
- $value = serialize($var);
- $timeout = time() + $expire;
- $result = safe_file_put_contents($this->cachePath . urlencode($key) .'.cache',
- $timeout . '<<%-==-%>>' . $value);
- return $result;
- }
- /**
- * 在cache中獲取鍵為$key的項的值
- * @param string $key 鍵值
- * @return string 如果該項不存在,則返回false
- * @access public
- */
- public function get($key) {
- $file = $this->cachePath . urlencode($key) .'.cache';
- if (file_exists($file)) {
- $content = safe_file_get_contents($file);
- if ($content===false) {
- return false;
- }
- $tmp = explode('<<%-==-%>>', $content);
- $timeout = $tmp[0];
- $value = $tmp[1];
- if (time()>$timeout) {
- $this->delete($key) ;//刪除文件過期的
- $result = false;
- } else {
- $result = unserialize($value);
- }
- } else {
- $result = false;
- }
- return $result;
- }
- /**
- * 清空cache中所有項
- * @return 如果成功則返回 TRUE,失敗則返回 FALSE。
- * @access public
- */
- public function flush() {
- $fileList = FileSystem::ls($this->cachePath,array(),'asc',true);
- return FileSystem::rm($fileList);
- }
- /**
- * 刪除在cache中鍵為$key的項的值
- * @param string $key 鍵值
- * @return 如果成功則返回 TRUE,失敗則返回 FALSE。
- * @access public
- */
- public function delete($key) {
- return FileSystem::rm($this->cachePath . $key .'.cache');
- }
- }
- if (!function_exists('safe_file_put_contents')) {
- function safe_file_put_contents($filename, $content)
- {
- $fp = fopen($filename, 'wb');
- if ($fp) {
- flock($fp, LOCK_EX);
- fwrite($fp, $content);
- flock($fp, LOCK_UN);
- fclose($fp);
- return true;
- } else {
- return false;
- }
- }
- }
- if (!function_exists('safe_file_get_contents')) {
- function safe_file_get_contents($filename)
- {
- $fp = fopen($filename, 'rb');
- if ($fp) {
- flock($fp, LOCK_SH);
- clearstatcache();
- $filesize = filesize($filename);
- if ($filesize > 0) {
- $data = fread($fp, $filesize);
- }
- flock($fp, LOCK_UN);
- fclose($fp);
- return $data;
- } else {
- return false;
- }
- }
- }
|
新聞熱點
疑難解答