Caching expensive actions with Jake

In an earlier post I described using the Jake bridge to get CakePHP working with Joomla. Overall the bridge works like a champ, with one exception I’ve found: it seems that Jake does not support cached actions – if you try to cache an action, it no longer renders through the Jake component. This is probably a bug in Jake.

Fortunately Jake does support cached elements though, so you can do this workaround to get your expensive operations cached.

  1. If you haven’t already, create the writable directory app/tmp/cache/views.
  2. Suppose your desired action is controllername/expensiveaction(). Move the logic into the new (private) function controllername/_expensiveactionimp() and make it return a $somedata variable that contains all the data you need to output. E.g.,
    function expensiveaction()
    {
      if (isset($this->params['requested']))
        return $this->_expensiveactionimp();
      else
      {
        // do other stuff
      }
    }
    function _expensiveactionimp()
    {
      // slow, expensive operations
      $somedata = do_slow_stuff();
      return $somedata;
    }
    
  3. Move the entire contents of the corresponding view to a new element: app/views/elements/expensiveaction.ctp. In this element, just do
    $somedata = $this->requestAction('controllername/expensiveaction);
  4. Now, in the view expensiveaction.ctp, just do (with the appropriate cache interval)
  5. echo $this->element('expensiveaction', array('cache' => '1 hour'));

Enjoy.

Leave a Reply

Your email address will not be published. Required fields are marked *