We 'mark up' sections in which we want to cache output by adding some conditional logic,
encapsulating the section within start() and end() methods (this
resembles the first example and is the core strategy for caching).
Inside, output your data as usual - all output will be cached when execution hits the end()
method. On the next run, the whole section will be skipped in favor of fetching data from cache
(as long as the cache record is valid).
<?php
$frontendOptions = array(
'lifetime' => 30, // cache lifetime of half a minute
'automatic_serialization' => false // this is default anyway
);
$backendOptions = array('cache_dir' => './tmp/');
$cache = Zend_Cache::factory('Output', 'File', $frontendOptions, $backendOptions);
// we pass a unique identifier to the start() method
if(!$cache->start('mypage')) {
// output as usual:
echo 'Hello world! ';
echo 'This is cached ('.time().') ';
$cache->end(); // the output is saved and sent to the browser
}
echo 'This is never cached ('.time().').';
Notice that we output the result of time() twice; this is something dynamic
for demonstration purposes. Try running this and then refreshing several times; you will notice
that the first number doesn't change while second changes as time passes. That is because the first
number was output in the cached section and is saved among other output.
After half a minute (we've set lifetime to 30 seconds) the
numbers should match again because the cache record expired -- only to be cached again. You
should try this in your brower or console.