php中apcu的替代
我在使用免费虚拟主机的过程中,自己的代码中,有涉及到使用apcu的部分,然后虚拟主机的环境都是服务商配好的,不能自助修改,导致代码执行出问题。
下面是用sqlite3代替apcu的替代方案。
if (!function_exists('apcu_store') || !ini_get('apc.enabled')) { $db = new SQLite3('cache.sqlite'); $db->exec('CREATE TABLE IF NOT EXISTS cache (key TEXT PRIMARY KEY, value TEXT, expire INTEGER)'); function apcu_store($key, $value, $ttl = 3600) { global $db; $stmt = $db->prepare('REPLACE INTO cache (key, value, expire) VALUES (:key, :value, :expire)'); $stmt->bindValue(':key', $key); $stmt->bindValue(':value', json_encode($value)); $stmt->bindValue(':expire', time() + $ttl); return $stmt->execute(); } function apcu_fetch($key) { global $db; $stmt = $db->prepare('SELECT value, expire FROM cache WHERE key = :key'); $stmt->bindValue(':key', $key); $result = $stmt->execute()->fetchArray(SQLITE3_ASSOC); if (!$result || $result['expire'] < time()) return false; return json_decode($result['value'], true); } }
先保存,后续在测试。