PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Zend Framework 101: Zend_Cache

Using the Cache

Now that you have a cache set up, you can read and write cache records.

To read data from the cache, use the load() method. This method accepts a cache ID as its first argument. This tells the cache which record is required.

If the record is found, the original data is returned. If you're using automatic serialization and the data you saved was something like a PHP array, then it will be automatically deserialized and you will receive it back in its original form.

If the record is not found then false is returned. You can easily test for this, and then generate the data if required. The data can then be saved to the cache using the save() method. This will make it available for subsequent calls to load().

The save() method accepts the data as its first argument. You can specify the cache ID as the second argument if you want to, but if you don't then the cache ID used in the load() call will be used.

Caution: If you're calling save() from a cache-priming script then you likely wouldn't have called load() ahead of time. In this case you should specify the cache ID as the second argument to save().

The following listing demonstrates making use of the load() and save() methods. To demonstrate the feel of slow code that caching is used to improve, I've added a call to PHP's sleep() function. This will make the first load slow (when it writes to cache) and subsequent loads (reading from cache) much faster.

Listing 4 Reading from and writing to the cache (listing-4.php)
<?php
    require_once('Zend/Cache.php');
 
    $frontendOptions = array(
        'automatic_serialization' => true
    );
 
    $backendOptions = array(
        'cache_dir' => './cache'
    );
 
    $cache = Zend_Cache::factory(
        'Core',
        'File',
        $frontendOptions,
        $backendOptions
    );
 
    // retrieve the input value
    $name = "Quentin";
 
    // generate the ID based on the input
    $cacheId = md5($name);
 
    // try and load the message from cache
    $message = $cache->load($cacheId);
 
    // check if cache miss occurred
    if ($message === false) {
        // simulate an expensive calculation
        sleep(2);
 
        // generate the message
        $message = sprintf('Hello %s', $name);
 
        // save the message to cache
        $cache->save($message);
    }
 
    // at this point we have the message, and it
    // belongs in the cache for next time
 
    // output the message
    echo $message . "\n";
?>

This demonstrates the most basic of cache usage. Next up we will look at some more advanced cache usage, including caching entire page output and using tags.

In This Article