[dev] Horde_Cache_file question

Vijay Mahrra vijay.mahrra at es.easynet.net
Mon Nov 8 02:37:52 PST 2004


Below is a snippet of code I have in the main driver class for an in-house application (it is
very specific to our systems here and not generic enough to warrant a submission to Horde)
which uses the wonderful Horde Application Framework.  Basically these functions are used to 
cache the results of a query (an array) for a time period of 1 day.

Trying to store the array using Horde_Cache returned an error because Horde_Cache expected a
string value, not an array.  I got around this by using serialize/unserialize php functions.
So it works OK.  

My question: is there a reason that Horde_Cache does not serialize/unserialize data automatically 
when a get/set call is made to the class? I think it would be a bit easier to use if the
action of serializing data was within the Horde_Cache class.  I can submit a patch if we are in
agreement.

This is the cache class I am using:

http://cvs.horde.org/co.php/framework/Cache/Cache/file.php?r=1.28


Vijay

    function &getCache() {
        global $conf;
        require_once 'Horde/Cache.php';
        if (!is_a($this->cache, 'Horde_Cache')) {
            $this->cache = &Horde_Cache::singleton($conf['cache']['driver'],
Horde::getDriverConfig('cache', $conf['cache']['driver']));
        }
        return $this->cache;
    }

    function &getFromCache($key, $lifetime = 17280) {
        $cache = $this->getCache();
        if (is_a($cache, 'PEAR_Error')) {
            return $cache;
        }
        $cache_data = $cache->get($key, $lifetime);
        if (is_a($cache_data, 'PEAR_Error')) {
            Horde::logMessage($cache_data, __FILE__, __LINE__, PEAR_LOG_ERR);
        }

        $log = sprintf("Retrieved %s from cache.", $key);
        Horde::logMessage($log, __FILE__, __LINE__, PEAR_LOG_NOTICE);
        return unserialize($cache_data);
    }

    function writeToCache($key, $value) {
        $cache = $this->getCache();
        if (is_a($cache, 'PEAR_Error')) {
            return $cache;
        }
        $msg = $cache->set($key, serialize($value));
        if (is_a($msg, 'PEAR_Error')) {
            return $msg;
        }
        $log = sprintf("Wrote %s to cache.", $key);
        Horde::logMessage($log, __FILE__, __LINE__, PEAR_LOG_NOTICE);
        return true;
    }


More information about the dev mailing list