• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

XF 2.0 Caches

katsulynx

Well-known member
#1
Is it recommended to use caches on items that are queried a lot but only change on very little occasions? I've been on the search for something similar as XF1's simpleCache, but only found the CacheFactory so far and wasn't able to figure out how to use it (probably because it's 4am). So... is it still recommended to do manual caching in XF2 or is this done by the repository-system already? I've seen the word 'cached' in the dev-docs a few times, but mostly only when it says 'to get the uncached value'. If so, can someone point me in the right direction (e.g. where a cache is initialized/updated in the core files)?
 

Xon

Well-known member
#2
@katsulynx Have a look at my XF2 add-on; Redis Cache which is an example of defining your own cache provider and how to cache some complex bits (forum thread list counts). The Finder system can make it challenging to cache those bits. But doable.

simpleCache exists, but you really should consider if you need the content on every page, css included before putting it in. It is also limited it ~16mb size but you should avoid pulling that amount of data every page load.

At the heart of it is simple, conditionally fetch the data if it exists, generate the data, save the cachable data.
Code:
$key = "MyKey";
if ($cache = \XF::app()->cache())
{    
    $data = $cache->fetch($key);
    if ($data)
    {
        return $data;
    }
}
$data = "some data";
if ($cache)
{
   $expiryInSeconds = 60;
   $cache->save($key, $expiryInSeconds);
}
return $data;
 

katsulynx

Well-known member
#3
Thanks, that was a great help! I plan on saving the frontend stuff of my fonts manager to the cache, as there's no need to do one to two database queries on every page call if you can shift that to the cache, so the storage/memory should be reasonable. But yes, fonts are needed on every page.
 
Last edited:

Xon

Well-known member
#5
@Xon \XF::app()->cache() returns null for me. Do I need to enable caching somewhere first?
Yes. FAQ for my RedisCache add-on has some sample configuration;

Code:
$config['cache']['enabled'] = true;
$config['cache']['provider'] = 'SV\RedisCache\Redis';
$config['cache']['config']  = array(
        'server' => '127.0.0.1',
        'port' => 6379,
    );
 

katsulynx

Well-known member
#6
That was simple. Turning $config['cache']['enabled'] = true; on seems to be enough for development. But I'm still thinking of simply throwing it into simpleCache though, as simpleCache is always available, independently of configuration...