发新话题
打印

PHP PEAR::Cache_Lite实现页面缓存

PHP PEAR::Cache_Lite实现页面缓存

PHP PEAR::Cache_Lite实现页面缓存
官方文档介绍,这个的缓存效率是很高的,"PEAR::Cache_Lite has to be extremely fast",具体怎么高呢?
我也没仔细看,不知道有没有王婆卖瓜的嫌疑。

PEAR::Cache List的特点:
1.simplicity
2.security

下面开始一个简单的缓存例子,让大家有个直接的认识。
复制内容到剪贴板
代码:
<?php
  require_once('Cache/Lite.php');
  //设置缓存文件存放的路径以及缓存有的效期(秒),确保此目录有写的权限,
  $option = array(
              'caching' => true,//默认为true
              'cacheDir' => 'D:/tmp/',
              'lifeTime' => 60);
  $cache = new Cache_Lite($option);
  //分区域缓存
  if($data = $cache->get('block1')) {
      echo($data);
  } else {
      $data = 'get block 1 contents from anywhere <br />';
      $cache->save($data);
  }
  echo('no cache text<br />');
  if($data = $cache->get('block2')) {
      echo($data);
  } else {
      $data = 'get block 2 contents from anywhere <br />';
      $cache->save($data);
  }
?>
Cache_Lite并不能保证总能重新获得缓存页面,因此推荐使用Cache_Lite_Output,它会直接输出,无需手工调用echo
下面用Cache_Lite_Output重写上面的例子:
复制内容到剪贴板
代码:
<?php
  require_once('Cache/Lite/Output.php');
  $option = array(
              'cacheDir' => 'D:/tmp/',
              'lifeTime' => 60);
  $cache = new Cache_Lite_Output($option);
  $cache->remove('bocck1');//清除以前的某块缓存
  if(! ($cache->start('block1'))) {
     echo('block 1 contents <br />');
      $cache->end();
  }
  echo('no cache text<br />');
  if(! ($cache->start('block2'))) {
     echo('block 2 contents <br />');
      $cache->end();
  }
  $cache->clean();//清除缓存
?>

为了确保Cache_Lite获得最大的效率,不要在输出缓存的时候包含其它的文件,仅仅在不需要缓存(重新计算)的时候包含其它的文件.
例如:
不正确的方法 :

<?php
   require_once("Cache/Lite.php");
   require_once("...")//包含了其它的文件
   require_once("...")
   // (...)
   $cache = new Cache_Lite();
   if ($data = $Cache_Lite->get($id)) { // cache hit !
       echo($data);
   } else { // page has to be (re)constructed in $data
       // (...)
       $Cache_Lite->save($data);
   }
?>
正确的使用方法:
复制内容到剪贴板
代码:
<?php
   require_once("Cache/Lite.php");
   // (...)
   $cache = new Cache_Lite();
   if ($data = $Cache_Lite->get($id)) { // cache hit !
       echo($data);
   } else { // page has to be (re)constructed in $data
       //重新计算的时候,包含其它文件
       require_once("...")
       require_once("...")
       // (...)
       $Cache_Lite->save($data);
   }
?>

TOP

发新话题