Zend_Cache

来源:互联网 发布:怎么判别淘宝托管被骗 编辑:程序博客网 时间:2024/05/23 18:14

1.Zend_Cache描述

Zend_Cache的基本使用方式:

$cache = Zend_Cache::factory('Core',                              'File',                              $frontendOptions,                              $backendOptions);得到缓存对对象。

Zend_Cache::factory方法有四个参数: 前端类型,后端类型,前端参数,后端参数。



zend_cache可以缓存什么?              

答:一个页面的输出Zend_Cache_Frontend_Output

一个方法(Zend_Cache_Frontend_Function)、

一个类(Zend_Cache_Frontend_Class)、

一个文件(Zend_Cache_Frontend_File)、

一个页面(Zend_Cache_Frontend_Page)、

还可以缓存从数据库查询出来的数据(zend手册上会有例子,可以发现前四个都继承至Zend_Cache_Core核心类)。每个类最后一个单词就是Zend_Cache::factory()的第一个参数前端类型,当然还有个核心累心Core,总共6个。


zend_cache缓存记录存放方式:

1.APC       

2.File       

3.Memcached         

4.Sqlite           

5.Xcache                 

  6.ZendPlatform 

这就是Zend_Cache::factory第二个参数后端类型




2.我的代码

最简单的一个例子

<?php$frontendOptions = array(   'lifeTime' => 7200, // 两小时的缓存生命期   'automatic_serialization' => true);$backendOptions = array(    'cache_dir' => './tmp/' // 放缓存文件的目录,在zend 框架中public/tmp目录下可以查看记录);// 取得一个Zend_Cache_Core 对象$cache = Zend_Cache::factory('Core',                              'File',                              $frontendOptions,                              $backendOptions);// 查看一个缓存是否存在:if(!$result = $cache->load('myresult11')) {    // 缓存不命中;连接到数据库    //$db = Zend_Db::factory( [...] );//这个自己连接你的数据库,为了方便我注释了,输出一句话。    $result = 'SELECT * FROM huge_table';    $cache->save($result, 'myresult11');} else {    // cache hit! shout so that we know    echo "This one is from cache!\n\n";}print_r($result);?>

第二个例子:前端类型是Output ,后端类型是File.

$frontendOptions = array(   'lifeTime' => 30,                  // cache lifetime of 30 seconds   'automatic_serialization' => false  // this is the default anyway s);// 翻译时实验系统为Windows,请使用Windows的读者修改cacheDir的路径为实际的路径$backendOptions = array('cache_dir' => './tmp/');$cache = Zend_Cache::factory('Output',                              'File',                              $frontendOptions,                              $backendOptions);// 传递一个唯一标识符给start()方法if(!$cache->start('mypage')) {    // output as usual:    echo 'Hello world! ';    echo 'This is cached ('.time().') ';    $cache->end(); // the output is saved and sent to the browser}echo 'This is never cached ('.time().').';




两次输出了time()的结果;为演示目的第二次的time()调用是动态的.再运行然后刷新多次;你会注意到当随着时间的流逝第一个数字并没有随时间改变.
这是因为第一个数组在缓存段中输出,因此输出是被缓存了. 30秒后(我们设置了lifetime为30秒)由于缓存纪录超时而变得无效了,第一个数字再次更新,
同时于第二个时间匹配(相同).你应该在你的浏览器或者控制台中试一下.


0 0
原创粉丝点击