How to use Zend_Cache to cache an object

June 18th, 2009

Warning: This post is 15 years old. Some of this information may be out of date.

Here's how to cache an object using Zend_Cache:

<?php
$cache_frontend_options = array(
            'lifetime' => 3600, // cache lifetime of 1 hour
            'automatic_serialization' => false
        );

$cache_backend_options = array(
            'servers' => array(
            array('host' => 'localhost', 'port' => 11211, 'persistent' => true)
            ),
            'compression' => false
        );

$cache = Zend_Cache::factory('Core', 'Memcached',
                $cache_frontend_options, $cache_backend_options);

$key = 'myUniqueId-123';
$cache_object = $cache->load($key);

 if ($cache_object === false) {
   // not in cache
    $object = new myObject();
    $cache->save(serialize($object), $key);
} else {
    // in cache
    $object = unserialize($cache_object);
}

Note: The reason that "automatic_serialization" is set to false and then I manually serialize and unserialize is that "automatic_serialization" didn't work.