主要的作用就是就是简化缓存操作,类型分文件缓存和memcache内存级缓存两种,能过常量进行相关配置
通过cache()函数进行缓存操作
PHP代码
- <?php
- //缓存存放类型
- define(‘CACHETYPE’, ‘file’);
- //memcache服务器地址
- define(‘MEMCACHE_HOST’,‘localhost’);
- //memcache服务器端口地址
- define(‘MEMCACHE_PORT’,11211);
- //文件类型缓存的话,设定存放位置
- define(‘CACHE_PATH’,‘cache/’);
- function cache($name,$var=”,$s=0)
- {
- $c=new cache;
- $name=str_replace(‘ ‘,”,substr($name,0,30)).‘_’.substr(md5($name),8,16);
- if(CACHETYPE==‘memcache’) return $c->memcacheCache($name,$var,$s);
- else return $c->fileCache($name,$var,$s);
- }
- class cache
- {
- function memcacheCacheRead($m,$name)
- {
- $return=$m->get($name);
- if(empty($return)) return false;
- else{
- return $return;
- }
- }
- function memcacheCache($name,$var,$s)
- {
- $m=self::memcache();
- if(empty($var)){
- return self::memcacheCacheRead($m,$name);
- }else{
- $m->set($name,$var,0,$s);
- return self::memcacheCacheRead($m,$name);
- }
- }
- function fileCache($name,$var,$s)
- {
- $filename=CACHE_PATH.$name.‘.php’;
- if(empty($var)){
- if(file_exists($filename)){
- return self::readCache($filename);
- }else return false;
- }else{
- if($this->writeCache($filename,$var,$s)){
- return self::readCache($filename);
- }else
- throw new Exception(‘File cache write error!’);
- }
- }
- function writeCache($filename,$var,$s)
- {
- $var=array(‘var’=>$var,‘s’=>$s);
- $content=serialize($var);
- $content=‘<?php exit;?>’.$content;
- fclose(fopen($filename,‘w’));
- if(file_put_contents($filename,$content)){
- return true;
- }else{
- return false;
- }
- }
- function readCache($filename)
- {
- $content=@file_get_contents($filename);
- $var=unserialize(str_replace(‘<?php exit;?>’,”,$content));
- $mtime=filemtime($filename);
- if(time()-$mtime>=$var[‘s’]){
- @unlink($filename);
- return false;
- }else{
- return $var[‘var’];
- }
- }
- function memcache()
- {
- $mem = new Memcache;
- $mem->connect(MEMCACHE_HOST,MEMCACHE_PORT) or die("Memcache could not connect");
- return $mem;
- }
- }
- //演示
- if(!$name=cache("name")){
- $name=cache("name",‘test memcache’,20);
- }
- print_r($name);
- ?>