7.Zeng_Cache(1) --- 简介

来源:互联网 发布:fission for mac 编辑:程序博客网 时间:2024/06/05 07:06

4.1 简介

Zend_Cache 提供了一个缓存任何数据的一般方法. 在Zend Framework中缓存由前端操作,同时通过后端适配器(File, Sqlite, Memcache...)和 一个灵活的IDs和Tags系统(标识符和标记系统)存储缓存纪录.使用此方法,易于删除特定类型的纪录(例如:"删除所有标记为tag的纪录") 模块(Zend_Cache_Core) 的核心是通用,灵活和可配置.对于特定的需要,为了便捷,这里有一些继承自Zend_Cache_Core的前端: Output, File, Function 和 Class. 

例 4.1. 调用 Zend_Cache::factory()取得一个前端

Zend_Cache::factory() 实例化正确的对象并把他们捆绑到一起. 在这第一个例子中我们将把 Core 前端和 File 后端一起使用. 
<?phprequire_once 'Zend/Cache.php';$frontendOptions = array(   'lifeTime' => 7200, // cache lifetime of 2 hours   'automatic_serialization' => true);$backendOptions = array(    'cache_dir' => './tmp/' // Directory where to put the cache files   缓存文件的路径);// 取得一个Zend_Cache_Core 对象$cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);?>

这里写图片描述


例 4.2. Caching a database query result

现在有了一个前端,可用缓存任何类型的数据了(开了序列化'serialization').例如,能够缓存从昂贵的数据库查询中缓存一个结果.结果被缓存后,不再需要连接到数据库;数据直接在缓存中取回和反序列化. 
<?php// $cache 在先前的例子中已经初始化了// 查看一个缓存是否存在:if(!$result = $cache->load('myresult')) {    // 缓存不命中;连接到数据库    $db = Zend_Db::factory( [...] );    $result = $db->fetchAll('SELECT * FROM huge_table');    $cache->save($result, 'myresult');} else {    // cache hit! shout so that we know    echo "This one is from cache!\n\n";}print_r($result);?>

例 4.3. 用Zend_Cache 输出前端缓存输出

通过加入条件逻辑,我们'mark up'(标记)那些希望缓存输出的段(sections),在start() 和end()方法间封装这些section(这类似第一个例子,并且是缓存的核心策略). 在内部,像往常一样输出你的数据,当执行到end()方法时,所有之前的输出都被缓存.在下一次运行时,整个段(end()方法调用前的代码)将被跳过执行,直接从Cache中取回数据(只要缓存纪录是有效的). 
<?php$frontendOptions = array(   'lifeTime' => 30,                  // cache lifetime of half a minute   'automatic_serialization' => false  // this is default anyway);// 翻译时实验系统为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().').';?>  

这里写图片描述


http://www.cnblogs.com/terryglp/articles/1959483.html

http://wenku.baidu.com/link?url=X6LBO3khljOx5OD4aCcomCbw_Ixepqtnt5XNmKeVWr1iB84CK-dd-aSuRdCLS93QHbKMfQ0-dzhN6cXBc4l9kgup7cyIhHyoZNC0Hg-VI1O

0 0