如何设置Zend Cache Storage的到期时间?

时间:2013-09-03 16:09:52

标签: php zend-framework2 zend-cache

我想将一些XML存储在Zend文件系统缓存中,并在30分钟后过期。如何设置缓存持续时间/到期?我使用Zend缓存作为组件,而不是在完整的ZF2应用程序的上下文中。

$cache   = \Zend\Cache\StorageFactory::factory(array(
    'adapter' => array(
        'name' => 'filesystem',
        'ttl' => 60, // kept short during testing
        'options' => array('cache_dir' => __DIR__.'/cache'),
    ),
    'plugins' => array(
        // Don't throw exceptions on cache errors
        'exception_handler' => array(
            'throw_exceptions' => false
        ),
    )
));
$key    = 'spektrix-events';   
$events = new SimpleXMLELement($cache->getItem($key, $success));

if (!$success) {
    $response = $client->setMethod('GET')->send();
    $events = new SimpleXMLElement($response->getContent());
    $cache->setItem('spektrix-events', $events->asXML());
}


var_dump($cache->getMetadata($key)); // the mtime on the file stays the same as does timestamp from ls -al in a terminal.

如何设置过期时间,然后检查缓存是否已过期?上面的代码似乎没有在60秒后使缓存失效(.dat文件的时间戳不会改变)

1 个答案:

答案 0 :(得分:8)

您是否尝试在适配器选项中设置选项ttl

'adapter' => array(
    'name' => 'filesystem',
    'options' => array(
        'cache_dir' => __DIR__.'/cache',
        'ttl' => 3600,
    ),
),

ZF documentation甚至还有很好的快速启动示例,其中提供了TTL。

更新

我测试了下一个脚本,TTL正在按照它应该的方式工作。你在其他地方有问题。

$cache = Zend\Cache\StorageFactory::factory(array(
    'adapter' => array(
        'name'    => 'filesystem',
        'options' => array('ttl' => 5),
    ),
));

$cache->setItem('a', 'b');
for ($i = 1; $i <= 7; $i++) {
    sleep(1);
    echo "var_dump on {$i}th second ... ";
    var_dump($cache->getItem('a'));
}

输出是:

var_dump on 1th second ... string(1) "b"
var_dump on 2th second ... string(1) "b"
var_dump on 3th second ... string(1) "b"
var_dump on 4th second ... string(1) "b"
var_dump on 5th second ... NULL
var_dump on 6th second ... NULL
var_dump on 7th second ... NULL