Zend_db缓存

时间:2012-02-04 21:52:37

标签: zend-framework zend-db zend-cache

有没有办法在Zend Db中缓存结果集?例如,我想使用Zend Db运行一个select查询,并希望缓存此查询以便以后能够更快地运行它。

2 个答案:

答案 0 :(得分:4)

我的建议是在Bootstrap.php中创建一个带有前缀“_init”的初始化方法。为exaple:

/**
 * 
 * @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.
}

答案 1 :(得分:2)

如果要保存结果集,可以使用Zend_Cache。

Zend_Db本身不进行任何结果集缓存。它留给你以特定于应用程序的方式执行它,因为框架无法知道出于性能原因需要缓存哪些结果集,而不是无法缓存的结果集需要它们绝对是最新的。这些是您应用程序开发人员所知道的标准。

只需使用Google搜索“zend_db缓存结果”,第一个匹配就是此博客显示如何使用Zend_Cache对象保存数据库查询结果:Zend Framework:: Caching the database query results

相关问题