Custom Caching in symfony

Just quickly, because it's handy and simple.

I'm building a page that's reading a twitter-feed to display on the front page. I don't want to be hitting twitter on every page hit though (obviously), so we need to cache the data. Could it be any simpler? (Thanks symfony! *cheesy wink*)

Let's dive into the code:

<?php
public function executeIndex()
{
    $cache = new sfFileCache(array('cache_dir' => '/tmp/twitter'));

    if (!$cache->has('tweet'))
    {
        $status = TwitterFeed::getLatestTweet(sfConfig::get('app_twitter_user_id'));
        $cache->set('tweet', $status, 600); // 10 mins cache expiry
    }

    $this->status = $cache->get('tweet', '');
}


Holy crap, that was too easy!

That said, it'd be stupid if it were any harder.

Now, a few tweaks you could do. You could, instead of caching to /tmp, you could cache to sf_cache_dir, so that a symfony cc would also clear that cached data. Could be handy, but might not be what you want.

I suppose if you weren't so lazy, you'd pull those out into app.yml variables. I would, if I were you! It's a pity I'm lazy, really.

Thursday, February 21. 2008

0 Comments