Monday, August 8, 2011

Use ApcCache to cache any PHP data in Symfony2

APC is the most well-known caching system for PHP, and maybe one of the simpliest. Symfony2 strongly suggests to enable it, as well on development than production environment.

Sf2 natively uses APC to cache PHP files as OPCODE. But you can cache what you want in your code, any kind of PHP data.

APC makes the distinction between PHP OPCODE cache and custom cache :
  • File cache gets PHP OPCODE,
  • User cache gets what developer decides to cache.

Here is an example of a controller action displaying some RSS streams on a homepage. We don't want to load the stream each time a user browses homepage so we put in cache the whole response (!) :

    * Route ; _home_rssNews
    * @return Symfony\Component\HttpFoundation\Response
   public function rssAction()
      //We get the cache before anything else
      $cacheDriver = new ApcCache();

      //If the cache exists and is not expired for _home_rssNews, we simply return its content !

      if ($cacheDriver->contains('_home_rssNews'))
         return $cacheDriver->fetch('_home_rssNews');

      //If not, we build the Response as usual and then put it in cache !

      $viewVars = array ();

      // FLUX RSS BLOG
      $rssB = $this->fluxRssBlog('my_blog_rss_stream'));
      $rssT = $this->fluxRssTwitter('my_twitter_rss_stream'));

      $viewVars['rssB'] = $rssB;
      $viewVars['rssT'] = $rssT;
      $response = $this->render('XxxYourBundle:Default:rssNews.html.twig', $viewVars);

      //We put this response in cache for a 15 minutes period !
      $cacheDriver->save('_home_rssNews', $response, "900");

      return $response;

No comments :

Post a Comment

Comments are moderated before being published.