mixable
mixable

Reputation: 1158

CakePHP: CacheHelper and themed views

In a CakePHP (2.1) app I'm using themes together with cacheAction. When accessing the view of e.g. /controller/action, its cache file is saved to tmp/views/controller_action.php. When accessing the same view from a mobile url (like m.example.com), I internally use the same app with themed views to simplify the output for the mobile device.

But now there is a problem with the cache: both requests have different hostnames and themes, but the same controller/action and therefore the same filename of the cache files. So when accessing the urls with different hosts or themes, CakePHP returns the same cache file (or more precisely the cache file of the first request). It is not possible to change the name of the cache files depending on a parameter (e.g. hostname or theme).

I tried modifying the parameters of CacheHelper, but without success. Is there a way to change the cache path/prefix for CacheHelper on the fly? Or is there another possibility to realize this behavior?

Upvotes: 1

Views: 648

Answers (2)

mixable
mixable

Reputation: 1158

Better solution: CakePHP 2.3 now supports a cache prefix in core config:

Configure::write('Cache.viewPrefix', 'YOURPREFIX');

This prefix may be adapted to match the theme name or some other parameters that are different in those requests.

Upvotes: 1

mixable
mixable

Reputation: 1158

The only workaround to solve this problem are the following steps:

1) Create an own MyCacheHelper that extends CacheHelper and save it to app/View/Helper/CacheHelper.php. Overwrite the method _writeFile() and extend the row of the $path string with your prefix:

App::uses('Helper', 'Cache');
class MyCacheHelper extends CacheHelper
{
  public function _writeFile($content, $timestamp, $useCallbacks = false)
  {
    // ...
    $cache = $prefix.strtolower(Inflector::slug($path));
    // ...
  }
}

2) Create an own MyDispatcher that extends Dispatcher and save it to app/Lib/Routing/MyDispatcher.php. Overwrite the method cached() and extend the row of the $path string with your prefix:

App::uses('Dispatcher', 'Routing');
class MyDispatcher extends Dispatcher
{
  public function cached($path)
  {
    // ...
    $path = $prefix.strtolower(Inflector::slug($path));
    // ...
  }
}

3) Change the file app/webroot/index.php to use your new dispatcher:

App::uses('MyDispatcher', 'Routing');
$Dispatcher = new MyDispatcher();

4) Update the $helper parameter in your controllers to use MyCache instead of Cache.

That's it. A little bit complicated, but it works as expected! Now you can adjust the $prefix to whatever you need and create unique cache files for e.g. different domains.

Upvotes: 1

Related Questions