Home Backend Development PHP Tutorial 强大的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='
Copy after login
    '; 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); } } ?>

?基于文件的

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

After joining the company, I understood what Cache is After joining the company, I understood what Cache is Jul 31, 2023 pm 04:03 PM

The thing is actually like this. At that time, my leader gave me a perf hardware performance monitoring task. During the process of using perf, I entered the command perf list and I saw the following information: My task is to enable these cache events to be counted normally. But the point is, I have no idea what these misses and loads mean.

What does function mean? What does function mean? Aug 04, 2023 am 10:33 AM

Function means function. It is a reusable code block with specific functions. It is one of the basic components of a program. It can accept input parameters, perform specific operations, and return results. Its purpose is to encapsulate a reusable block of code. code to improve code reusability and maintainability.

Fix: Snipping tool not working in Windows 11 Fix: Snipping tool not working in Windows 11 Aug 24, 2023 am 09:48 AM

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

How to Fix Can't Connect to App Store Error on iPhone How to Fix Can't Connect to App Store Error on iPhone Jul 29, 2023 am 08:22 AM

Part 1: Initial Troubleshooting Steps Checking Apple’s System Status: Before delving into complex solutions, let’s start with the basics. The problem may not lie with your device; Apple's servers may be down. Visit Apple's System Status page to see if the AppStore is working properly. If there's a problem, all you can do is wait for Apple to fix it. Check your internet connection: Make sure you have a stable internet connection as the "Unable to connect to AppStore" issue can sometimes be attributed to a poor connection. Try switching between Wi-Fi and mobile data or resetting network settings (General > Reset > Reset Network Settings > Settings). Update your iOS version:

Why does using cache increase computer speed? Why does using cache increase computer speed? Dec 09, 2020 am 11:28 AM

Using the cache can increase the speed of the computer because the cache shortens the waiting time of the CPU. Cache is a small but high-speed memory located between the CPU and the main memory DRAM. The function of Cache is to increase the rate of CPU data input and output; Cache has a small capacity but fast speed, while the memory speed is low but has a large capacity. By optimizing the scheduling algorithm, the performance of the system will be greatly improved.

What is cache? What is cache? Nov 25, 2022 am 11:48 AM

Cache is called cache memory. It is a high-speed small-capacity memory between the central processing unit and the main memory. It is generally composed of high-speed SRAM. This kind of local memory is oriented to the CPU. It is introduced to reduce or eliminate the gap between the CPU and the memory. The impact of the speed difference between them on system performance. Cache capacity is small but fast, memory speed is low but capacity is large. By optimizing the scheduling algorithm, the performance of the system will be greatly improved.

nginx reverse proxy caching tutorial. nginx reverse proxy caching tutorial. Feb 18, 2024 pm 04:48 PM

Here is the tutorial for nginx reverse proxy caching: Install nginx: sudoaptupdatesudoaptinstallnginx Configure reverse proxy: Open nginx configuration file: sudonano/etc/nginx/nginx.conf Add the following configuration in the http block to enable caching: http{...proxy_cache_path /var/cache/nginxlevels=1:2keys_zone=my_cache:10mmax_size=10ginactive=60muse_temp_path=off;proxy_cache

See all articles