Cached json (or xml) view with CakePHP

While implementing caching for view as descriped in the cookbook i stumbled upon some glitches:

First I found out the best way to avoid problems with routing urls beeing not cached – especially when using Router::mapResources() – is to enable the caching per action in the controller like this:

function view($id = null) {
$this->cacheAction = “10 minutes”;
// more stuff
}

The next problem was that cached views don’t retain document mime type (xml, json, etc.). The first request works correctly (uncached request), but the second request will come back as text/html. You can find a more detailed description of the problem here.

I got an advice to enable callbacks for my views but that slows down and defeats the purpose of the cache. My approach now is to use a layout like this:

[php]

[/php]

With the header(‘Content-type: text/x-json’); embedded in the nocache tags, it works fast and returns the correct mime type.

  • Development-Server XDebug enabled, APC enabled, View cache disabled:
    Requests per second: 1.64 [#/sec]
  • Development-Server XDebug enabled, APC enabled, View cache enabled (files):
    Requests per second: 29.04 [#/sec]
  • Development-Server XDebug disabled, APC enabled, View cache enabled (files):
    Requests per second: 95.66 [#/sec]

Further reading
8 Ways to Speed Up the Performance of CakePHP Apps.
Store View Cache in APC or Memcached.

3 comments Write a comment