简介
在Zend Framework中缓存由前端操作,同时通过后端适配器(
模块( Example #1 调用
$frontendOptions = array(
'lifeTime' => 7200, // 两小时的缓存生命期
'automatic_serialization' => true
);
$backendOptions = array(
'cache_dir' => './tmp/' // 放缓存文件的目录
);
// 取得一个Zend_Cache_Core 对象
$cache = Zend_Cache::factory('Core',
'File',
$frontendOptions,
$backendOptions);
Example #2 Caching a database query result 现在有了一个前端,可用缓存任何类型的数据了(开了序列化'serialization').例如,能够缓存从昂贵的数据库查询中缓存一个结果.结果被缓存后,不再需要连接到数据库;数据直接在缓存中取回和反序列化.
// $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);
Example #3 用
通过加入条件逻辑,我们'mark up'(标记)那些希望缓存输出的段(sections),在
在内部,像往常一样输出你的数据,当执行到
$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().').';
注意我们两次输出了
|