Multiget/intelligent generic PHP wrapper function... thoughts/advice wanted

Chris Goffinet goffinet at yahoo-inc.com
Sat Nov 3 05:19:49 UTC 2007


The array_values is not needed, its already an array. Just set it up  
as $key=>$value and do not do extra overhead.


Chris Goffinet
goffinet at yahoo-inc.com



On Nov 2, 2007, at 10:15 PM, mike wrote:

> On 11/2/07, Chris Goffinet <goffinet at yahoo-inc.com> wrote:
>> Yes because doing a hash lookup is much faster than looping +
>> str_replace. You increase memory but that is the tradeoff.
>
> okay, here's revised. thoughts?
>
> function episode_get($keys) {
>        $prefix = 'episodes:';
>        list($hits, $misses) = cache_get($prefix, $keys);
>        if(count($misses) > 0) {
>                if(is_array($misses)) {
>                        $misses = implode(',', $misses);
>                }
>                $q = db_query("SELECT * FROM episodes WHERE ID  
> IN($misses)");
>                if(db_numrows($q) == 0) {
>                        return false;
>                } else {
>                        while($r = db_rows_assoc($q)) {
>                                cache_set($prefix.$r['ID'], $r);
>                                $hits[] = $r;
>                        }
>                }
>        }
>        return $hits;
> }
>
> function cache_get($prefix, $keys) {
>
>        $cache_keys_prefix = array();
>        $cache_keys = array();
>
>        if(!isset($GLOBALS['ch'])) {
>                 cache_open();
>        }
>
>        if(!is_array($keys)) {
>                $keys = Array($keys);
>        }
>
>        foreach(array_values($keys) as $key) {
>                $cache_keys_prefix[$prefix.$key] = $prefix.$key;
>                $cache_keys[$prefix.$key] = $key;
>        }
>
>        $cache_hits = memcache_get($GLOBALS['ch'], $cache_keys_prefix);
>        $cache_diffs = array_diff_key($cache_keys, $cache_hits);
>
>        return array($cache_hits, $cache_diffs);
> }
>
> function cache_set($key, $value, $flags = 0, $expiry = 2592000) {
>        if(!isset($GLOBALS['ch'])) {
>                 cache_open();
>        }
>        memcache_set($GLOBALS['ch'], $key, $value, $flags, $expiry);
> }



More information about the memcached mailing list