简体   繁体   English

Symfony2简单结果缓存?

[英]Symfony2 simple result cache?

I need a really simple Key-Value-Cache in Symfony. 我在Symfony中需要一个非常简单的键值缓存。 Something like that, without any Doctrine or HTTP-caching. 像这样,没有任何教义或HTTP缓存。

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

Did I miss it in the manual or do I need another bundle? 我是否在手册中错过了它,还是需要另一个捆绑包?

Why do you not google? 你为什么不谷歌? Or take a look at knpbundles.com and search there for "Cache": 或访问knpbundles.com并在此处搜索“缓存”:

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

Maybe this is something for your needs: 也许这是您需要的东西:

https://github.com/winzou/CacheBundle https://github.com/winzou/CacheBundle

Usage: 用法:

$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');

Edit: 编辑:

It's not a good idea to use the session for this. 为此使用会话不是一个好主意。 Session is per user and cached values can not be shared. 会话是针对每个用户的,无法共享缓存的值。 And when you use the session you have to think about serialization and other problems that can occurred when you store complex object in session. 当您使用会话时,您必须考虑序列化以及在会话中存储复杂对象时可能发生的其他问题。

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

I've used the LiipDoctrineCache which although it utilises the Doctrine cache, it supports multiple data stores - including the file system and APC. 我使用了LiipDoctrineCache,尽管它利用了Doctrine缓存,但它支持多个数据存储-包括文件系统和APC。

https://github.com/liip/LiipDoctrineCacheBundle https://github.com/liip/LiipDoctrineCacheBundle

Here's how I use it to cache external API responses: 这是我用来缓存外部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'));

From Symfony documentation: 从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 http://symfony.com/doc/master/components/http_foundation/sessions.html

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

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