时光绘梦集
位置:首页PHP正文

道法自然 2025/04/22 周2

php按需加载缓存扩展

哎,一套代码更换了服务器环境就经常因为加载的扩展的不同,导致一些代码出问题。

比如缓存,使用缓存可以减少系统的重复计算,比如一个计算结果,或者读取的数据库的配置信息,第一次获取之后,一段时间内,都是不会修改的,如果每次重复读取或者计算就会浪费系统资源,所以缓存就存在了。

我目前使用的缓存,一般也就是apcu,memcached,redis,编一段代码,可以检测扩展,自动使用对应的缓存,即使后续发生其他变化了,只需要修改这段代码就可以。

<?php
interface cache {
    public function set($key, $value, $ttl);
    public function get($key);
}

class ApcuCache implements cache {
    public function set($key, $value, $ttl) {
        return apcu_store($key, $value, $ttl);
    }

    public function get($key) {
        return apcu_fetch($key);
    }
}

class MemcachedCache implements cache {
    private static $instance = null;

    private function __construct() {
        $this->memcached = new Memcached();
        $this->memcached->addServer('localhost', 11211);
    }

    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new MemcachedCache();
        }
        return self::$instance;
    }

    public function set($key, $value, $ttl) {
        return $this->memcached->set($key, $value, $ttl);
    }

    public function get($key) {
        return $this->memcached->get($key);
    }
}

class RedisCache implements cache {
    private static $instance = null;

    private function __construct() {
        $this->redis = new Redis();
        $this->redis->connect('127.0.0.1', 6379);
    }

    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new RedisCache();
        }
        return self::$instance;
    }

    public function set($key, $value, $ttl) {
        return $this->redis->setex($key, $ttl, $value);
    }

    public function get($key) {
        return $this->redis->get($key);
    }
}

function getcaches() {
    static $cache=null;
if($cache===null){
    $cacheTypes = [
        'apcu' => ApcuCache::class,
        'memcached' => MemcachedCache::class,
        'redis' => RedisCache::class,
    ];
    $cache=false;
    foreach ($cacheTypes as $extension => $class) {
        if (extension_loaded($extension)) {
            $cache=new $class();
            break;
        }
    }
}
    return $cache;
}

function caset($key, $value, $ttl = 0) {
    $cache = getcaches();
    if ($cache) {
        return $cache->set($key, $value, $ttl);
    }
    return false;
}

function caget($key) {
    $cache = getcaches();
    if ($cache) {
        return $cache->get($key);
    }
    return false;
}

使用方法

caset($key,$value,3600);#设置
$value=caget($key);#获取


上一篇:代码压缩
下一篇:太上老君内丹经