ViewFish PHP Templating Engine

Caching

ViewFish supports in-memory caching to reduce filesystem reads and speed up template loading. You'll need either Memcache or Memcached enabled on your server.

Enabling Cache

$mc = new Memcached();
$mc->addServer('localhost', 11211);

$t = new ViewFish\viewfish();
$t->enable_cache($mc, 3600);  // cache templates for 1 hour

The second argument is the TTL (time-to-live) in seconds. Defaults to 300 (5 minutes). Common values:

TTL Duration Use case
300 5 minutes Templates that change frequently
86400 1 day Stable templates
2592000 30 days Templates that rarely change

Once enabled, load_template() will check cache first and only hit the filesystem on a cache miss.

Cache Methods

Method Description
$t->enable_cache($mc, $ttl) Enable caching with a Memcache/Memcached object
$t->uncache($tmpl) Delete a cached uncompiled template
$t->cache_compiled(true) Enable caching of rendered (compiled) templates
$t->cache_compiled(false) Disable compiled template caching
$t->cache_create($tmpl, $text, $ttl) Manually store a compiled template
$t->cache_read($tmpl) Retrieve a compiled template from cache
$t->cache_destroy($tmpl) Delete a compiled template from cache

Compiled Template Caching

ViewFish can also cache fully rendered templates. This is useful for pages with no user-specific data (e.g., a shared footer or static content block).

$t->cache_compiled(true);

// Now every render() call will cache its output
$html = $t->render($template, $data);

Warning: If your template contains user-specific data (names, emails, personalized content), the cached output will be served to every visitor. Only use compiled caching for shared, non-personalized content.

Manual Cache Management

You can manually control what gets cached:

// Store a rendered template
$html = $t->render($template, $data);
$t->cache_create('my-page', $html, 86400);

// Later, retrieve it
$cached = $t->cache_read('my-page');
if ($cached) {
    echo $cached;
} else {
    // re-render and cache again
}

// Invalidate when content changes
$t->cache_destroy('my-page');