簡體   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