繁体   English   中英

Symfony2简单结果缓存?

[英]Symfony2 simple result cache?

我在Symfony中需要一个非常简单的键值缓存。 像这样,没有任何教义或HTTP缓存。

<?php
$cacheKey = 'blabla';
if(!$cache->has($cacheKey)) {
    // do some heavy work...
    $cache->set($cacheKey, $heavyWorkResult);
}
$result = $cache->get($cacheKey);

我是否在手册中错过了它,还是需要另一个捆绑包?

你为什么不谷歌? 或访问knpbundles.com并在此处搜索“缓存”:

http://knpbundles.com/search?q=Cache

也许这是您需要的东西:

https://github.com/winzou/CacheBundle

用法:

$cache = $this->get('winzou_cache.apc');
// or
$cache = $this->get('winzou_cache.file');
// or
$cache = $this->get('winzou_cache.memcache');
// or
$cache = $this->get('winzou_cache.array');
// or
$cache = $this->get('winzou_cache.xcache');
// or
$cache = $this->get('winzou_cache.zenddata');
// or
$cache = $this->get('winzou_cache'); // in that case, it will use the default driver     defined in config.yml, see below

$cache->save('bar', array('foo', 'bar'));

if ($cache->contains('bar')) {
    $bar = $cache->fetch('bar');
}

$cache->delete('bar');

编辑:

为此使用会话不是一个好主意。 会话是针对每个用户的,无法共享缓存的值。 当您使用会话时,您必须考虑序列化以及在会话中存储复杂对象时可能发生的其他问题。

我认为您可以使用https://github.com/doctrine/cache (教义现在独立使用的缓存系统)

我使用了LiipDoctrineCache,尽管它利用了Doctrine缓存,但它支持多个数据存储-包括文件系统和APC。

https://github.com/liip/LiipDoctrineCacheBundle

这是我用来缓存外部API响应的方法:

$cache_driver = $container->get('liip_doctrine_cache.ns.YOUR_NAME');

if ($cache_driver->contains($cache_key)) {
   return $this->cache_driver->fetch($cache_key);
}

// Do something expensive here...

$cache_driver->save($cache_key, "Mixed Data", strtotime('4 hours'));

从Symfony文档中:

use Symfony\Component\HttpFoundation\Session\Session;

$session = new Session();
$session->start();

// set and get session attributes
$session->set('name', 'Drak');
$session->get('name');

http://symfony.com/doc/master/components/http_foundation/sessions.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM