简体   繁体   中英

Symfony2 simple result cache?

I need a really simple Key-Value-Cache in Symfony. Something like that, without any Doctrine or HTTP-caching.

<?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":

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

Maybe this is something for your needs:

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.

https://github.com/liip/LiipDoctrineCacheBundle

Here's how I use it to cache external API responses:

$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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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