您不需要压缩每个文件启用输出压缩 php.ini
并自动完成
zlib.output_compression = On
或启动输出缓冲区
ob_start('ob_gzhandler');
现在,如果缓存的目的是因为speed
然后storage space
不使用文件系统,只需使用 Memcached .. 它支持内置压缩
$memcache = new Memcache();
$memcache->addserver("127.0.0.1");
$memcache->add($filename, ob_get_contents(), MEMCACHE_COMPRESSED);
更新
这是一个管理文件缓存和内存缓存的简单脚本......您可以轻松地将其扩展到其他类型的存储,例如 mongoDB 或 redis
使用文件系统
$storage = new Fcache();
$storage->setDir(__DIR__ . "/cache"); // cache directory
使用内存缓存
$storage = new Mcache();
$storage->addserver("127.0.0.1"); // Add Server
你的脚本
$cache = new SimpleCache($storage);
$cache->setTime(5); // 5 sec for demo
if ($data = $cache->get()) {
echo "Cached Copy <br />\n";
echo $data;
} else {
ob_start();
while(@$i ++ < 10) {
echo mt_rand();
}
$cache->set(ob_get_contents());
ob_end_flush();
}
如您所见,$storage
存储可以是文件或内存缓存,这是使用的类
简单缓存
class SimpleCache {
private $storage;
function __construct(CacheStorage $storage) {
$this->storage = $storage;
}
public function setTime($time) {
$this->storage->setTime($time);
}
function get() {
$name = sha1($_SERVER['REQUEST_URI']) . ".cache";
return $this->storage->read($name);
}
function set($content) {
$name = sha1($_SERVER['REQUEST_URI']) . ".cache";
$this->storage->write($name, $content);
}
}
贮存
interface CacheStorage {
public function setTime($time);
public function read($file);
public function write($file, $data);
}
// Using Memcache
class Mcache extends Memcache implements CacheStorage {
private $time = 86400;
public function setTime($time) {
$this->time = $time;
}
public function read($name) {
return $this->get($name);
}
public function write($name, $data) {
return $this->add($name, $data, MEMCACHE_COMPRESSED, $this->time);
}
}
// Using Files System
class Fcache implements CacheStorage {
private $dir;
private $time = 86400;
public function __construct($dir = "cache") {
$this->setDir($dir);
}
public function setDir($dir) {
$this->dir = $dir;
if (! is_dir($this->dir) and ! mkdir($this->dir))
throw new Exception("Invalid Directory");
$this->dir = $dir;
}
public function setTime($time) {
$this->time = $time;
}
public function read($name) {
$name = $this->dir . "/" . $name;
if (! is_file($name))
return false;
if (time() - filemtime($name) > $this->time)
return false;
$zd = gzopen($name, "r");
$zr = "";
while(! feof($zd)) {
$zr .= gzread($zd, 1024);
}
gzclose($zd);
return $zr;
}
public function write($name, $data) {
$name = $this->dir . "/" . $name;
touch($name);
$gz = gzopen($name, "w9");
gzwrite($gz, $data);
gzclose($gz);
return true;
}
}