Skip to content

cache static html

Harmen Janssen edited this page Jun 8, 2016 · 2 revisions

Static cache controller actions

Add the following to your controller:

public function init() {
    $this->_helper->cache(array('index', 'termsandconditions', 'about'));
}

Where the various names in the array are controller actions. This will save requests to those actions as HTML files in /public/cached/.

In order to clear these cached files, you must tag certain paths with model names. Changes to these models will then automatically clear the cache. Add these tags to /application/configs/cache.ini, like this:

; Cinema
staticcaching.tags.Model_Cinema[] = "index.html"
staticcaching.tags.Model_Cinema[] = "events.html"

(index.html is the cached version of a call to /, while events.html refers to /events)

; Event
staticcaching.tags.Model_Event[] = "events*"
staticcaching.tags.Model_Event[] = "zoek*"

; Genre
staticcaching.tags.Model_Genre[] = "events.html"
staticcaching.tags.Model_Genre[] = "films.html"

Note that the paths can contain wildcards. Under the hood these paths are fed directly to bash's rm – to give you an idea how to format these paths. You should choose paths created from actions that read from the given model.

Caching JSON output

Note that by default cache files are stored as HTML files. Sometimes your app will return JSON (or any other output for that matter) and in this case you can add some parameters to the cache helper's call:

$this->_helper->cache($actions, array(), 'json');

This instructs the cache helper to create a JSON file instead of an HTML file. The .htaccess file does not by default read these JSON files, so you should add something like the following in order to actually read the cache files:

# JSON output from API
RewriteCond %{REQUEST_URI} /api/ [OR]
RewriteCond %{REQUEST_URI} as_json
RewriteCond %{DOCUMENT_ROOT}/cached/%{REQUEST_URI}.json -f
RewriteRule .* cached/%{REQUEST_URI}.json [L,T=text/javascript]
Clone this wiki locally