【发布时间】:2012-02-27 00:41:51
【问题描述】:
有没有办法在 Zend_db 中缓存结果集?例如,我想使用 Zend_db 运行一个选择查询,并希望缓存这个查询以便以后能够更快地运行它。
【问题讨论】:
标签: zend-framework zend-db zend-cache
有没有办法在 Zend_db 中缓存结果集?例如,我想使用 Zend_db 运行一个选择查询,并希望缓存这个查询以便以后能够更快地运行它。
【问题讨论】:
标签: zend-framework zend-db zend-cache
我的建议是在 Bootstrap.php 中创建一个带有前缀“_init”的初始化方法。例如:
/**
*
* @return Zend_Cache_Manager
*/
public function _initCache()
{
$cacheManager = new Zend_Cache_Manager();
$frontendOptions = array(
'lifetime' => 7200, // cache lifetime of 2 hours
'automatic_serialization' => true
);
$backendOptions = array(
'cache_dir' => APPLICATION_PATH . '/cache/zend_cache'
);
$coreCache = Zend_Cache::factory(
'Core',
'File',
$frontendOptions,
$backendOptions
);
$cacheManager->setCache('coreCache', $coreCache);
$pageCache = Zend_Cache::factory(
'Page',
'File',
$frontendOptions,
$backendOptions
);
$cacheManager->setCache('pageCache', $pageCache);
Zend_Registry::set('cacheMan', $cacheManager);
return $cacheManager;
}
通过这种方式,您已创建缓存管理器并将其注入应用中所需的缓存。 现在你可以在你想使用的地方使用这个缓存对象了。 例如,在您的控制器或其他地方:
/**
*
* @return boolean |SimplePie
*/
public function getDayPosts()
{
$cacheManager = Zend_Registry::get('cacheMan');
$cache = $cacheManager->getCache('coreCache');
$cacheID = 'getDayPosts';
if (false === ($blog = $cache->load($cacheID))) {
$blog = Blog::find(array('order' => 'rand()', 'limit' => 1));
$cache->save($blog, $cacheID);
}
// do what you want to do with the daya you fetched.
}
【讨论】:
当你想保存结果集时,你可以使用 Zend_Cache。
Zend_Db 本身不做任何结果集缓存。留给您以特定于应用程序的方式进行操作,因为框架无法知道哪些结果集出于性能原因需要缓存,而那些无法因为您需要它们绝对是最新的。这些是只有您作为应用程序开发人员知道的标准。
只需在谷歌上搜索“zend_db 缓存结果”,第一个匹配项就是这个博客,它展示了如何使用 Zend_Cache 对象来保存 db 查询结果:Zend Framework:: Caching the database query results
【讨论】: