検索
ホームページバックエンド開発PHPチュートリアル強力な PHP キャッシュ (eaccelerator、apc、xcache、memcache モジュール キャッシュ)

強力な PHP キャッシュ クラス (eaccelerator、apc、xcache、memcache モジュール キャッシュ)

<?php /*
 * Name:    wrapperCache
 * URL:     http://www.admpub.com/
 * Version: v0.1
 * Date:    29/10/2010
 * Author:  Chema Garrido
 * License: GPL v3
 * Notes:   wrapper cache for fileCache, memcache, APC, Xcache and eaccelerator
 */
 
class wrapperCache {
    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='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 'eaccelerator':
                @eaccelerator_clean();
                @eaccelerator_clear();
            break;
 
            case 'apc':
                apc_clear_cache('user');
            break;
 
            case 'xcache':
                xcache_clear_cache(XC_TYPE_VAR, 0);
            break;
 
            case 'memcache':
                @$this->cache_external->flush();
            break;
             
            case 'filecache':
                $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 'eaccelerator':
                eaccelerator_put($key, serialize($data), $ttl);
            break;
 
            case 'apc':
                apc_store($key, $data, $ttl);
            break;
 
            case 'xcache':
                xcache_set($key, serialize($data), $ttl);
            break;
 
            case 'memcache':
                $data=serialize($data);
                if (!$this->cache_external->replace($key, $data, false, $ttl))
                $this->cache_external->set($key, $data, false, $ttl);
            break;
             
            case 'filecache':
                $this->cache_external->cache($key,$data);
            break;
        }  
    }
     
    //returns cache for the given key
    private function get($key){
        switch($this->cache_type){
            case 'eaccelerator':
                $data =  @unserialize(eaccelerator_get($key));
            break;
 
            case 'apc':
                $data =  apc_fetch($key);
            break;
 
            case 'xcache':
                $data =  @unserialize(xcache_get($key));
            break;
 
            case 'memcache':
                $data = @unserialize($this->cache_external->get($key));
            break;
             
            case 'filecache':
                $data = $this->cache_external->cache($key);
            break;
        }  
        /*echo '<br>--returnning data for key:'.$key;
        var_dump($data);*/
        return $data;
    }
     
    //delete key from cache
    public function delete($key){
        switch($this->cache_type){
            case 'eaccelerator':
                eaccelerator_rm($key);
            break;
 
            case 'apc':
                apc_delete($key);
            break;
 
            case 'xcache':
                xcache_unset($key);
            break;
 
            case 'memcache':
                $this->cache_external->delete($key);
            break;
             
            case 'filecache':
                $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->$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 'eaccelerator':
                if (function_exists('eaccelerator_get')) $this->cache_type = 'eaccelerator';
                else $this->cacheError('eaccelerator not found');   
            break;
 
            case 'apc':
                if (function_exists('apc_fetch')) $this->cache_type = 'apc' ;
                else $this->cacheError('APC not found'); 
            break;
 
            case 'xcache':
                if (function_exists('xcache_get')) $this->cache_type = 'xcache' ;
                else $this->cacheError('Xcache not found');
            break;
 
            case 'memcache':
                if (class_exists('Memcache')) $this->init_memcache();
                else $this->cacheError('memcache not found');
            break;
             
            case 'filecache':
                if (class_exists('fileCache'))$this->init_filecache();
                else $this->cacheError('fileCache not found');
            break;
             
            case 'auto'://try to auto select a cache system
                if (function_exists('eaccelerator_get'))    $this->cache_type = 'eaccelerator';                                      
                elseif (function_exists('apc_fetch'))       $this->cache_type = 'apc' ;                                    
                elseif (function_exists('xcache_get'))      $this->cache_type = 'xcache' ;                                       
                elseif (class_exists('Memcache'))           $this->init_memcache();
                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
                if (isset($type)) $msg='Unrecognized cache type selected <b>'.$type.'</b>';
                else $msg='Not any cache type selected';
                $this->cacheError($msg);    
            break;
        }
    }  
         
    private function init_memcache(){//get instance of the memcache class
        if (is_array($this->cache_params)){
            $this->cache_type = 'memcache';
            $this->cache_external = new Memcache;
            foreach ($this->cache_params as $server) {
                $server['port'] = isset($server['port']) ? (int) $server['port'] : ini_get('memcache.default_port');
                $server['persistent'] = isset($server['persistent']) ? (bool) $server['persistent'] : true;
                $this->cache_external->addServer($server['host'], $server['port'], $server['persistent']);
            }
        }
        else $this->cacheError('memcache needs an array, example:
                    wrapperCache::GetInstance(\'memcache\',30,array(array(\'host\'=>\'localhost\')));');
    }
     
    private function init_filecache(){//get instance of the filecache class
        $this->cache_type = 'filecache';
        $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('eaccelerator',function_exists('eaccelerator_get'));                                      
        $avCaches[] = array('apc',function_exists('apc_fetch')) ;                                    
        $avCaches[] = array('xcache',function_exists('xcache_get'));                                       
        $avCaches[] = array('memcache',class_exists('Memcache'));
        $avCaches[] = array('fileCache',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); } } ?>

?ファイルベース

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
function是什么意思function是什么意思Aug 04, 2023 am 10:33 AM

function是函数的意思,是一段具有特定功能的可重复使用的代码块,是程序的基本组成单元之一,可以接受输入参数,执行特定的操作,并返回结果,其目的是封装一段可重复使用的代码,提高代码的可重用性和可维护性。

修复:截图工具在 Windows 11 中不起作用修复:截图工具在 Windows 11 中不起作用Aug 24, 2023 am 09:48 AM

为什么截图工具在Windows11上不起作用了解问题的根本原因有助于找到正确的解决方案。以下是截图工具可能无法正常工作的主要原因:对焦助手已打开:这可以防止截图工具打开。应用程序损坏:如果截图工具在启动时崩溃,则可能已损坏。过时的图形驱动程序:不兼容的驱动程序可能会干扰截图工具。来自其他应用程序的干扰:其他正在运行的应用程序可能与截图工具冲突。证书已过期:升级过程中的错误可能会导致此issu简单的解决方案这些适合大多数用户,不需要任何特殊的技术知识。1.更新窗口和Microsoft应用商店应用程

入职后,我才明白什么叫Cache入职后,我才明白什么叫CacheJul 31, 2023 pm 04:03 PM

事情其实是这样的,当时领导交给我一个perf硬件性能监视的任务,在使用perf的过程中,输入命令perf list,我看到了以下信息:我的任务就要让这些cache事件能够正常计数,但关键是,我根本不知道这些misses、loads是什么意思。

如何修复无法连接到iPhone上的App Store错误如何修复无法连接到iPhone上的App Store错误Jul 29, 2023 am 08:22 AM

第1部分:初始故障排除步骤检查苹果的系统状态:在深入研究复杂的解决方案之前,让我们从基础知识开始。问题可能不在于您的设备;苹果的服务器可能会关闭。访问Apple的系统状态页面,查看AppStore是否正常工作。如果有问题,您所能做的就是等待Apple修复它。检查您的互联网连接:确保您拥有稳定的互联网连接,因为“无法连接到AppStore”问题有时可归因于连接不良。尝试在Wi-Fi和移动数据之间切换或重置网络设置(“常规”>“重置”>“重置网络设置”>设置)。更新您的iOS版本:

使用cache可以提高计算机运行速度这是因为什么使用cache可以提高计算机运行速度这是因为什么Dec 09, 2020 am 11:28 AM

使用cache可以提高计算机运行速度这是因为Cache缩短了CPU的等待时间。Cache是位于CPU和主存储器DRAM之间,规模较小,但速度很高的存储器。Cache的功能是提高CPU数据输入输出的速率;Cache容量小但速度快,内存速度较低但容量大,通过优化调度算法,系统的性能会大大改善。

cache是什么存储器?cache是什么存储器?Nov 25, 2022 am 11:48 AM

cache叫做高速缓冲存储器,是介于中央处理器和主存储器之间的高速小容量存储器,一般由高速SRAM构成;这种局部存储器是面向CPU的,引入它是为减小或消除CPU与内存之间的速度差异对系统性能带来的影响。Cache容量小但速度快,内存速度较低但容量大,通过优化调度算法,系统的性能会大大改善。

Nginx缓存Cache的配置方案及相关内存占用问题怎么解决Nginx缓存Cache的配置方案及相关内存占用问题怎么解决May 23, 2023 pm 02:01 PM

nginx缓存cache的5种方案 1、传统缓存之一(404)  这个办法是把nginx的404错误定向到后端,然后用proxy_store把后端返回的页面保存。  配置:  location/{  root/home/html/;#主目录  expires1d;#网页的过期时间  error_page404=200/fetch$request_uri;#404定向到/fetch目录下  }  location/fetch/{#404定向到这里  internal;#指明这个目录不能在外部直接访

SpringBoot项目中怎么使用缓存CacheSpringBoot项目中怎么使用缓存CacheMay 16, 2023 pm 02:34 PM

前言缓存可以通过将经常访问的数据存储在内存中,减少底层数据源如数据库的压力,从而有效提高系统的性能和稳定性。我想大家的项目中或多或少都有使用过,我们项目也不例外,但是最近在review公司的代码的时候写的很蠢且low,大致写法如下:publicUsergetById(Stringid){Useruser=cache.getUser();if(user!=null){returnuser;}//从数据库获取user=loadFromDB(id);cahce.put(id,user);returnu

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール