您好,欢迎访问一九零五行业门户网

PHP缓存操作实例详解_PHP教程

为什么要使用缓存技术?理由很简单:提高效率。在程序开发中,获取信息的方式主要是查询数据库,除此以外,也可能是通过web services或者别的某种方法,无论哪种方法,在大量的并发访问面前,它们都可能成为效率的瓶颈,为了解决这些问题,人们提出了很多解决方案,其中一些是利用优化软件(如:apc,eaccelerator,zend optimizer等等)来提高程序的运行效率,合理的运用这些软件,往往能使程序的运行效率得到数量级上的提升,但前提是你必须拥主机的控制权,以便能够安装这些软件,如果你使用的是虚拟主机的话,那么只能祈祷你的服务提供商已经预装了某个优化软件,否则就必须自己使用php来实现相应的缓存功能。如果这让你感到无所适从,相信下面的这段缓存操作类的代码能给你一些有用的启发。(php缓存操作实例详解)
cachepath=emptyempty($path)?$this->cachepath:$path; $this->cachetime=emptyempty($time)?$this->cachetime:$time; $file=$this->cachepath.$id.'.php'; if(file_exists($file)){ //缓存过期 if((filemtime($file)+$time)returntype){ $row=include $file; }else{ $data=file_get_contents($file); $row=unserialize($data); } return $row; } return null;}/** * 写入缓存 * * @accesspublic * @param mixed$data缓存内容 * @returnbool是否写入成功 */ public function writecache($id,$data,$path=''){ $this->cachecount++; $id=md5($id); $this->cachepath=emptyempty($path)?$this->cachepath:$path; $file=$this->cachepath.$id.'.php'; chmod($this->cachepath,777); if(1===$this->returntype){ $data=''; }else{ $data=serialize($data); } return file_put_contents($file, $data);}/** * 删除指定缓存 * * @accesspublic * @param mixed$id缓存名称 * @returnbool是否删除成功 */ public function delcache($id,$path=''){ $id=md5($id); $this->cachepath=emptyempty($path)?$this->cachepath:$path; $file=$this->cachepath.$id.'.php'; if(file_exists($file)){ return unlink($file); } return null;}/** * 删除所有缓存 * * @accesspublic * @param mixed$dir缓存名称 * @returnbool清除所有缓存是否成功 */ public function delallcache($path=''){ $id=md5($id); $this->cachepath=emptyempty($path)?$this->cachepath:$path; $path=$this->cachepath; if(is_dir($path)){ if($dh=opendir($path)){ while(($file=readdir($dh))!==false){ if($file!='..'&$file!='.'){ if(is_dir($path.'/'.$file)){ if(!deldir($path.'/'.$file)){ return 0; } }else{ if(!unlink($path.'/'.$file)){ return 0; } } } } closedir($dh); } return 1; }}}
以上缓存操作类的引用方法如下:
writecache($id,$data);//读缓存并打印$name_row=$cache->readcache($id,120);print_r($name_row);//删除某个变量$cache->delcache($id);//删除全部缓存$cache->delallcache();
注意要保证cache目录(即缓存目录)存在并且可写。
您可能感兴趣的文章php获取当前操作系统类型用php函数memory_get_usage获取当前php内存消耗量以实现程序的性能优化php生成迅雷、快车、qq旋风下载链接的实例php如何判断当前的操作系统是linux还是windowsphp用ziparchive函数实现文件的压缩与解压缩php实现多重继承实例php缓存技术详解php获取目录所有文件并将结果保存到数组的程序
http://www.bkjia.com/phpjc/764165.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/764165.htmltecharticle为什么要使用缓存技术?理由很简单:提高效率。在程序开发中,获取信息的方式主要是查询数据库,除此以外,也可能是通过web services或...
其它类似信息

推荐信息