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

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

Jun 13, 2016 pm 01:09 PM
cache eaccelerator function gt this

強力な 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='<ul>';
            foreach ($avCaches as $c){
                $ret.='<li>'.$c[0].' - ';
                if ($c[1]) $ret.='Found/Compatible';
                else $ret.='Not Found/Incompatible';
                $ret.='</ll>';
            }
            return $ret.'</ul>';
        }
        else return $avCaches; 
    }
     
    private function cacheError($msg){//triggers error
        trigger_error('<br /><b>wrapperCache error</b>: '.$msg.
                    '<br />If you want you can try with \'auto\' for auto select a compatible cache.
                    <br />Or choose a supported cache from list:'.$this->getAvailableCache(), E_USER_ERROR);
    }
}
?> 
ログイン後にコピー

?ファイルベース

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

ホット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衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

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

SublimeText3 中国語版

SublimeText3 中国語版

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

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

Huawei GT3 ProとGT4の違いは何ですか? Huawei GT3 ProとGT4の違いは何ですか? Dec 29, 2023 pm 02:27 PM

多くのユーザーはスマートウォッチを選ぶときにファーウェイブランドを選択しますが、その中でもファーウェイ GT3pro と GT4 は非常に人気のある選択肢であり、多くのユーザーはファーウェイ GT3pro と GT4 の違いに興味を持っています。 Huawei GT3pro と GT4 の違いは何ですか? 1. 外観 GT4: 46mm と 41mm、材質はガラスミラー + ステンレススチールボディ + 高解像度ファイバーバックシェルです。 GT3pro: 46.6mm および 42.9mm、材質はサファイアガラス + チタンボディ/セラミックボディ + セラミックバックシェルです。 2. 健全な GT4: 最新の Huawei Truseen5.5+ アルゴリズムを使用すると、結果はより正確になります。 GT3pro: ECG 心電図と血管と安全性を追加

機能とはどういう意味ですか? 機能とはどういう意味ですか? Aug 04, 2023 am 10:33 AM

ファンクションとは、関数を意味します。これは、特定の関数を備えた再利用可能なコード ブロックです。プログラムの基本コンポーネントの 1 つです。入力パラメータを受け取り、特定の操作を実行し、結果を返すことができます。その目的は、再利用可能なコード ブロックをカプセル化することです。コードの再利用性と保守性を向上させるコード。

入社してキャッシュとは何かを理解した 入社してキャッシュとは何かを理解した Jul 31, 2023 pm 04:03 PM

実際は次のようなものです。当時、私のリーダーは私に perf ハードウェア パフォーマンス監視タスクを与えました。perf を使用するプロセス中に、コマンド perf list を入力すると、次の情報が表示されました。私のタスクは、これらのキャッシュ イベントを有効にすることです。しかし重要なのは、これらのミスやロードが何を意味するのか全く分からないということです。

修正: Windows 11 で Snipping ツールが機能しない 修正: Windows 11 で Snipping ツールが機能しない Aug 24, 2023 am 09:48 AM

Windows 11 で Snipping Tool が機能しない理由 問題の根本原因を理解すると、適切な解決策を見つけるのに役立ちます。 Snipping Tool が正しく動作しない主な理由は次のとおりです。 フォーカス アシスタントがオンになっている: これにより、Snipping Tool が開かなくなります。破損したアプリケーション: 起動時にスニッピング ツールがクラッシュする場合は、破損している可能性があります。古いグラフィック ドライバー: 互換性のないドライバーは、スニッピング ツールに干渉する可能性があります。他のアプリケーションからの干渉: 実行中の他のアプリケーションが Snipping Tool と競合する可能性があります。証明書の有効期限が切れています: アップグレード プロセス中のエラーにより、この問題が発生する可能性があります。これらの簡単な解決策は、ほとんどのユーザーに適しており、特別な技術知識は必要ありません。 1. Windows および Microsoft Store アプリを更新する

キャッシュを使用するとコンピュータの速度が向上するのはなぜですか? キャッシュを使用するとコンピュータの速度が向上するのはなぜですか? Dec 09, 2020 am 11:28 AM

キャッシュを使用すると、CPU の待ち時間が短縮されるため、コンピューターの速度が向上します。キャッシュは、CPU とメイン メモリ DRAM の間に位置する小さいながらも高速なメモリです。キャッシュの機能はCPUのデータ入出力速度を高めることであり、キャッシュは容量は小さいが速度が速く、メモリは速度は低いが容量が大きいため、スケジューリングアルゴリズムを最適化することでシステムのパフォーマンスを向上させることができます。大幅に改善されました。

キャッシュ、rom、ramの特徴は何ですか? キャッシュ、rom、ramの特徴は何ですか? Aug 26, 2022 pm 04:05 PM

キャッシュの特徴:CPUとメインメモリの間に設けられた1層または2層の高速かつ小容量のメモリで、コンピュータの電源を切ると情報は自然に失われます。 ROM の特性: メモリからデータを読み取ることのみが可能ですが、情報を書き込むことはできず、コンピュータの電源を切ってもデータは残ります。 ram の特性: メモリからデータを読み取り、メモリに情報を書き込むことができます。プログラムの実行に必要なコマンド、プログラム、およびデータを保存するために使用されます。コンピュータの電源がオフになると、情報は自然に失われます。

nginx リバースプロキシキャッシュのチュートリアル。 nginx リバースプロキシキャッシュのチュートリアル。 Feb 18, 2024 pm 04:48 PM

nginx リバース プロキシ キャッシュのチュートリアルは次のとおりです。 nginx のインストール: sudoaptupdatesudoaptinstallnginx リバース プロキシの構成: nginx 構成ファイルを開きます: sdonano/etc/nginx/nginx.conf キャッシュを有効にするには、http ブロックに次の構成を追加します: http{...proxy_cache_path /var/cache/nginxlevels=1:2keys_zone=my_cache:10mmax_size=10ginactive=60muse_temp_path=off;proxy_cache

SpringBootプロジェクトでキャッシュを使用する方法 SpringBootプロジェクトでキャッシュを使用する方法 May 16, 2023 pm 02:34 PM

Preface キャッシュは、頻繁にアクセスされるデータをメモリに保存し、データベースなどの基盤となるデータ ソースへの負担を軽減することで、システムのパフォーマンスと安定性を効果的に向上させることができます。誰もがプロジェクトで多かれ少なかれこれを使用したことがあると思いますが、私たちのプロジェクトも例外ではありませんでしたが、最近会社のコードをレビューしていたとき、非常に愚かでレベルの低い記述でした。 {Useruser=cache.getUser();if(user!=null){returnuser;}//データベースからユーザーを取得=loadFromDB(id);cahce.put(id,user);returnu

See all articles