Curious Rami

CakePHP Main Page Caching Workaround

July 24, 2007 · 3 Comments

CakePHP has a great caching helper with one annoying bug; the main page located at “/” never gets cached because the cache helper tries to name the cache file .php (null) and fails.

SiteAMonth (http://www.siteamonth.com/archives/2007/02/21/cakephp-cache-workarounds-part-1/) has found a solution with a little problem:

This does generate an extra request due to the redirect. The optimal solution is to fix this in the CakePHP core. Once I have a better understanding of the cache code I may suggest a fix, assuming someone doesn’t beat me to it.

Here is my solution which requires modifying two files in CakePHP framework build cake_1.1.16.5421:

On line 206 of \cake\libs\view\helpers\cache.php change:

if (empty($cache)) {
  return;
}

To:

if (empty($cache)) {
  /*Modified by Rami Nasser */
  /*”rami” is the main page cache file name*/
  $cache = “rami”;
  /*return;*/
}

On line 90 of \cake\bootstrap.php

After:

if (empty($uri)) {
  $uri = setUri();
}

Add:

/*Added by Rami Nasser*/
if($uri == “/”) {
  /*”rami” is the main page cache file name*/
  $uri = “rami”;
}

I used “rami” for the cache file name because… Anyways make up your own.

Let me know what you think.

Categories: CakePHP

3 responses so far ↓

  • Rami Nasser // July 24, 2007 at 6:30 pm

    Notes:

    The cache time is defined in your controller:

    var $cacheAction = array(
    ‘index’ => 21600,
    );

    And make sure you specify the action in your route even if it is index, otherwise you will get a warning when the cache expires:

    $Route->connect(’/', array(’controller’ => ‘posts’, ‘action’ => ‘index’));

  • Beth // July 24, 2007 at 11:26 pm

    Hi Rami,

    Just came across your post!

    Are saying even if you specify the actual router for “/”, that cake won’t cache the home page?

    If so, do you know if this has been reported as a bug?

    Beth

  • Rami Nasser // July 24, 2007 at 11:35 pm

    The page will be cached ok the first time, however, when trying to access the cache after it expired, the dispatcher gives a warning on line ~93 that it is missing the action, so we need to tell it explicitly that the action is index.

    To reproduce the wanting:

    -Apply my fix
    -Open the main page in a browser to cache it
    -Go into the cache file and change the time to a past date (more than the cache time ago)
    -Open the main page in a browser. Here: the page will be cached and a warning will show on the top

You must be logged in to post a comment.