在Zend Framework中使用Cache

时间:2013-02-04 10:18:16

标签: php zend-framework caching

有人可以简单地告诉我在Zend Framework 1.x中添加缓存/启用缓存吗?即可理解且易于实施的解决方案。感谢。

2 个答案:

答案 0 :(得分:0)

设置缓存:

$frontend= array(
    'lifetime' => 60,
    'automatic_serialization' => true
);

$backend= array(
    'cache_dir' => 'D:\cache',
);

$cache = Zend_Cache::factory('core', 'File', $frontend, $backend );
Zend_Registry::set('cache',$cache);

用它来设置:

private function setCached($key, $data)
{
    $cache = Zend_Registry::get('cache');
    $cache->save($data, $key);
}

使用它来获取:

private function getCached($key)
{
    $cache = Zend_Registry::get('cache');
    if(!$result = $cache->load($key)) 
    {
        return false;
    } 
    else 
    {
        return $result;
    }
}

答案 1 :(得分:0)

Zend Cache提供一种在缓存中存储数据并提高速度的非常简单的方法。 Zend使用Frontend和Back端来缓存。 前端对于访问或操作缓存很有用。 后端对于在File,Memcache,Sqlite等中存储数据非常有用。

首先通过在bootstrap文件中创建on函数来初始化前端和备份的引导程序文件。

受保护的功能_initCache(){

    $frontend= array(
        'lifetime' => 7200,
        'automatic_serialization' => true
    );

    $backend= array(
        'cache_dir' => '../application/tmp/',
    );

    $cache = Zend_Cache::factory('core',
            'File',
            $frontend,
            $backend
    );
    Zend_Registry::set('cache',$cache);
}

然后使用zend缓存工厂来定义缓存对象。 参数核心定义了通用类型的zend缓存核心手段 File参数是定义缓存存储意味着存储缓存记录的位置 然后第二个是前端和后端。

现在使用zend注册表注册该缓存数组,以便您可以在任何控制器,模型等中使用它。

在任何控制器或任何想要使用数据缓存的模型中定义以下代码。

    $result1 =””;
    $cache = Zend_Registry::get('cache');

if(!$result1 = $cache->load('mydata')) {
        echo 'caching the data…..';
    $data=array(1,2,3);
    $cache->save($data, 'mydata');
} else {
    echo 'retrieving cache data…….';
    Zend_Debug::dump($result1);
}

首先在上面的代码中我们得到了缓存数组。 现在,如果未设置结果1,则缓存完成意味着文件是在后端数组中定义的路径生成的

对于下一次页面加载,从缓存数据存储的文件中检索数据。

您可以按照定义的路径检查文件。

在该文件中,数据采用json格式。