0

0

PHP比较全面的缓存类

巴扎黑

巴扎黑

发布时间:2016-11-24 15:12:04

|

1278人浏览过

|

来源于php中文网

原创

php

/*

 * Name:    wrapperCache

 * Notes:   wrapper cache for fileCache, memcache/memcached, APC, Xcache and eaccelerator

$cacheObj =wrapperCache::getInstance('memcache',30,array(array('host'=>'localhost')));

立即学习PHP免费学习笔记(深入)”;

echo $cacheObj->cache('key','value');

*/

class wrapperCache {

    const DEFAULT_MEMCACHE_PORT     = 11211;

    const CACHE_TYPE_AUTO           = 'auto';

    const CACHE_TYPE_EACCELERATOR   = 'eaccelerator';

    const CACHE_TYPE_APC            = 'apc';

    const CACHE_TYPE_MEMCACHE       = 'memcache';

    const CACHE_TYPE_MEMCACHED      = 'memcached';

    const CACHE_TYPE_FILE           = 'filecache';

    const CACHE_TYPE_XCACHE         = 'xcache';

    private $cache_params;   //extra params for external caches like path or connection option memcached

    public  $cache_expire;   //seconds that the cache expires

    private $cache_type;     //type of cache to use

    private $cache_external; //external instance of cache, can be fileCache or memcache

    private static $instance;//Instance of this class

    // Always returns only one instance

    public static function getInstance($type=self::CACHE_TYPE_AUTO, $exp_time=3600, $params='cache/'){

        if (!isset(self::$instance)) { //doesn't exists the isntance

            self::$instance = new self($type, $exp_time, $params); //goes to the constructor

        }

        return self::$instance;

    }

    //cache constructor, optional expiring time and cache path

    private function __construct($type, $exp_time, $params) {

        $this->cache_expire = $exp_time;

        $this->cache_params = $params;

        $this->setCacheType($type);

    }

    public function __destruct() {

        unset($this->cache_external);

    }

    // Prevent users to clone the instance

    public function __clone(){

        $this->cacheError('Clone is not allowed.');

    }

    //deletes cache from folder

    public function clearCache(){

        switch($this->cache_type){

            case self::CACHE_TYPE_EACCELERATOR :

                eaccelerator_clean();

                eaccelerator_clear();

                break;

            case self::CACHE_TYPE_APC :

                apc_clear_cache('user');

                break;

            case self::CACHE_TYPE_XCACHE :

                xcache_clear_cache(XC_TYPE_VAR, 0);

                break;

            case self::CACHE_TYPE_MEMCACHE :

                $this->cache_external->flush();

                break;

            case self::CACHE_TYPE_MEMCACHED :

                $this->cache_external->flush();

                break;

            case self::CACHE_TYPE_FILE:

                $this->cache_external->deleteCache();

                break;

        }

    }

    //writes or reads the cache

    public function cache($key, $value = '', $ttl = '') {

        if ($value != '') { //wants to write

            if ($ttl == '') $ttl = $this->cache_expire;

            $this->put($key, $value, $ttl);

        } else return $this->get($key);

        //reading value

    }

    //creates new cache files with the given data, $key== name of the cache, data the info/values to store

    private function put($key, $data, $ttl = '') {

        if ($ttl == '') $ttl = $this->cache_expire;

        switch($this->cache_type){

            case self::CACHE_TYPE_EACCELERATOR :

                eaccelerator_put($key, serialize($data), $ttl);

                break;

            case self::CACHE_TYPE_APC :

                apc_store($key, $data, $ttl);

                break;

            case self::CACHE_TYPE_XCACHE :

                xcache_set($key, serialize($data), $ttl);

                break;

            case self::CACHE_TYPE_MEMCACHE :

                $data=serialize($data);

                $this->cache_external->set($key, $data, false, $ttl);

                break;

            case self::CACHE_TYPE_MEMCACHED :

                $data=serialize($data);

                $this->cache_external->set($key, $data, $ttl);

                break;

            case self::CACHE_TYPE_FILE :

                $this->cache_external->cache($key,$data);

                break;

        }

    }

    //returns cache for the given key

    private function get($key){

        switch($this->cache_type){

            case self::CACHE_TYPE_EACCELERATOR :

                $data =  unserialize(eaccelerator_get($key));

                break;

            case self::CACHE_TYPE_APC :

                $data =  apc_fetch($key);

                break;

            case self::CACHE_TYPE_XCACHE :

                $data =  unserialize(xcache_get($key));

                break;

            case self::CACHE_TYPE_MEMCACHE :

                $data = unserialize($this->cache_external->get($key));

                break;

            case self::CACHE_TYPE_MEMCACHED :

                $data = unserialize($this->cache_external->get($key));

                break;

            case self::CACHE_TYPE_FILE :

                $data = $this->cache_external->cache($key);

                break;

        }

        return $data;

    }

    //delete key from cache

    public function delete($key){

        switch($this->cache_type){

            case self::CACHE_TYPE_EACCELERATOR :

                eaccelerator_rm($key);

网奇.NET网络商城系统
网奇.NET网络商城系统

系统优势: 1、 使用全新ASP.Net+c#和三层结构开发. 2、 可生成各类静态页面(html,htm,shtm,shtml和.aspx) 3、 管理后台风格模板自由选择,界面精美 4、 风格模板每月更新多套,还可按需定制 5、 独具的缓存技术加快网页浏览速度 6、 智能销售统计,图表分析 7、 集成国内各大统计系统 8、 多国语言支持,内置简体繁体和英语 9、 UTF-8编码,可使用于全球

下载

                break;

            case self::CACHE_TYPE_APC :

                apc_delete($key);

                break;

            case self::CACHE_TYPE_XCACHE :

                xcache_unset($key);

                break;

            case self::CACHE_TYPE_MEMCACHE :

                $this->cache_external->delete($key);

                break;

            case self::CACHE_TYPE_MEMCACHED :

                $this->cache_external->delete($key);

                break;

            case self::CACHE_TYPE_FILE :

                $this->cache_external->delete($key);

                break;

        }

    }

    // Overloading for the Application variables and automatically cached

    public function __set($name, $value) {

        $this->put($name, $value, $this->cache_expire);

    }

    public function __get($name) {

        return $this->get($name);

    }

    public function __isset($key) {//echo "Is '$name' set?\n"

        if ($this->get($key) !== false)  return true;

        else return false;

    }

    public function __unset($name) {//echo "Unsetting '$name'\n";

        $this->delete($name);

    }

    //end overloads

    public function getCacheType(){

        return $this->cache_type;

    }

    //sets the cache if its installed if not triggers error

    public function setCacheType($type){

        $this->cache_type=strtolower($type);

        switch($this->cache_type){

            case self::CACHE_TYPE_EACCELERATOR :

                if (!function_exists('eaccelerator_get')) $this->cacheError('eaccelerator not found');

                break;

            case self::CACHE_TYPE_APC :

                if (!function_exists('apc_fetch')) $this->cacheError('APC not found');

                break;

            case self::CACHE_TYPE_XCACHE :

                if (function_exists('xcache_get')) $this->cacheError('Xcache not found');

                break;

            case self::CACHE_TYPE_MEMCACHE :

                if (class_exists('Memcache')) $this->init_mem();

                else $this->cacheError('memcache not found');

                break;

            case self::CACHE_TYPE_MEMCACHED :

                if (class_exists('Memcached')) $this->init_mem(true);

                else $this->cacheError('memcached not found');

                break;

            case self::CACHE_TYPE_FILE :

                if (class_exists('fileCache'))$this->init_filecache();

                else $this->cacheError('fileCache not found');

                break;

            case self::CACHE_TYPE_AUTO ://try to auto select a cache system

                if (function_exists('eaccelerator_get'))    $this->cache_type = self::CACHE_TYPE_EACCELERATOR;

                elseif (function_exists('apc_fetch'))       $this->cache_type = self::CACHE_TYPE_APC ;

                elseif (function_exists('xcache_get'))      $this->cache_type = self::CACHE_TYPE_XCACHE;

                elseif (class_exists('Memcache'))           $this->init_mem();

                elseif (class_exists('Memcached'))          $this->init_mem(true);

                elseif (class_exists('fileCache'))          $this->init_filecache();

                else $this->cacheError('not any compatible cache was found');

                break;

            default://not any cache selected or wrong one selected

                $msg='Not any cache type selected';

                if (isset($type)) $msg='Unrecognized cache type selected '.$type.'';

                $this->cacheError($msg);

                break;

        }

    }

    private function init_mem($useMemecached = false) { //get instance of the memcache/memcached class

        if (is_array($this->cache_params)) {

            if ($useMemecached) {

                $this->cache_type = self::CACHE_TYPE_MEMCACHED;

                $this->cache_external = new Memcached();

            } else {

                $this->cache_type = self::CACHE_TYPE_MEMCACHE;

                $this->cache_external = new Memcache;

            }

            foreach ($this->cache_params as $server) {

                $server['port'] = isset($server['port']) ? (int)$server['port'] : self::DEFAULT_MEMCACHE_PORT;

                if ($useMemecached) {

                    $this->cache_external->addServer($server['host'], $server['port']);

                } else {

                    $server['persistent'] = isset($server['persistent']) ? (bool)$server['persistent'] : true;

                    $this->cache_external->addServer($server['host'], $server['port'], $server['persistent']);

                }

            }

        } else $this->cacheError($this->cache_type . ' needs an array, example:wrapperCache::getInstance("' . $this->cache_type . '",30,array(array("host"=>"localhost")));');

    }

    private function init_filecache(){//get instance of the filecache class

        $this->cache_type = self::CACHE_TYPE_FILE ;

        $this->cache_external = fileCache::getInstance($this->cache_expire, $this->cache_params);

    }

    public function getAvailableCache($return_format='html'){//returns the available cache

        $avCaches   = array();

        $avCaches[] = array(self::CACHE_TYPE_EACCELERATOR,function_exists('eaccelerator_get'));

        $avCaches[] = array(self::CACHE_TYPE_APC,         function_exists('apc_fetch')) ;

        $avCaches[] = array(self::CACHE_TYPE_XCACHE,      function_exists('xcache_get'));

        $avCaches[] = array(self::CACHE_TYPE_MEMCACHE,    class_exists('Memcache'));

        $avCaches[] = array(self::CACHE_TYPE_MEMCACHED,   class_exists('Memcached'));

        $avCaches[] = array(self::CACHE_TYPE_FILE,        class_exists('fileCache'));

        if ($return_format == 'html') {

            $ret = '

    ';

                foreach ($avCaches as $c) {

                    $ret .= '

  • ' . $c[0] . ' - ';

                    if ($c[1]) $ret .= 'Found/Compatible';

                    else $ret .= 'Not Found/Incompatible';

                    $ret .= '';

                }

                return $ret . '

';

        } else return $avCaches;

    }

    private function cacheError($msg){//triggers error

        trigger_error('
wrapperCache error: '.$msg.

            '
If you want you can try with \'auto\' for auto select a compatible cache.

                   
Or choose a supported cache from list:'.$this->getAvailableCache(), E_USER_ERROR);

    }

}

相关文章

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

php

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
1688阿里巴巴货源平台入口与批发采购指南
1688阿里巴巴货源平台入口与批发采购指南

本专题整理了1688阿里巴巴批发进货平台的最新入口地址与在线采购指南,帮助用户快速找到官方网站入口,了解如何进行批发采购、货源选择以及厂家直销等功能,提升采购效率与平台使用体验。

60

2026.02.06

快手网页版入口与电脑端使用指南 快手官方短视频观看入口
快手网页版入口与电脑端使用指南 快手官方短视频观看入口

本专题汇总了快手网页版的最新入口地址和电脑版使用方法,详细提供快手官网直接访问链接、网页端操作教程,以及如何无需下载安装直接观看短视频的方式,帮助用户轻松浏览和观看快手短视频内容。

15

2026.02.06

C# 多线程与异步编程
C# 多线程与异步编程

本专题深入讲解 C# 中多线程与异步编程的核心概念与实战技巧,包括线程池管理、Task 类的使用、async/await 异步编程模式、并发控制与线程同步、死锁与竞态条件的解决方案。通过实际项目,帮助开发者掌握 如何在 C# 中构建高并发、低延迟的异步系统,提升应用性能和响应速度。

8

2026.02.06

Python 微服务架构与 FastAPI 框架
Python 微服务架构与 FastAPI 框架

本专题系统讲解 Python 微服务架构设计与 FastAPI 框架应用,涵盖 FastAPI 的快速开发、路由与依赖注入、数据模型验证、API 文档自动生成、OAuth2 与 JWT 身份验证、异步支持、部署与扩展等。通过实际案例,帮助学习者掌握 使用 FastAPI 构建高效、可扩展的微服务应用,提高服务响应速度与系统可维护性。

4

2026.02.06

JavaScript 异步编程与事件驱动架构
JavaScript 异步编程与事件驱动架构

本专题深入讲解 JavaScript 异步编程与事件驱动架构,涵盖 Promise、async/await、事件循环机制、回调函数、任务队列与微任务队列、以及如何设计高效的异步应用架构。通过多个实际示例,帮助开发者掌握 如何处理复杂异步操作,并利用事件驱动设计模式构建高效、响应式应用。

7

2026.02.06

java连接字符串方法汇总
java连接字符串方法汇总

本专题整合了java连接字符串教程合集,阅读专题下面的文章了解更多详细操作。

25

2026.02.05

java中fail含义
java中fail含义

本专题整合了java中fail的含义、作用相关内容,阅读专题下面的文章了解更多详细内容。

28

2026.02.05

控制反转和依赖注入区别
控制反转和依赖注入区别

本专题整合了控制反转和依赖注入区别、解释、实现方法相关内容。阅读专题下面的文章了解更多详细教程。

20

2026.02.05

钉钉脑图插图教程合集
钉钉脑图插图教程合集

本专题整合了钉钉脑图怎么插入图片、钉钉脑图怎么用相关教程,阅读专题下面的文章了解更多详细内容。

60

2026.02.05

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
PHP课程
PHP课程

共137课时 | 11.1万人学习

JavaScript ES5基础线上课程教学
JavaScript ES5基础线上课程教学

共6课时 | 11.2万人学习

PHP新手语法线上课程教学
PHP新手语法线上课程教学

共13课时 | 0.9万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号