views:

209

answers:

2

Hi, I'm using PDO for connect to the database in a system where I want implement memcached.

I don't know what keys use for caching the results because I can't get the string of the final query with PDO (because the prepared statements).

Any good idea for resolve this?

Thanks in advance.

A: 

Here is interesting tutorial it might be helpful - http://techportal.ibuildings.com/2009/02/16/getting-started-with-memcached/

I guess you can automate the process by implementing a function like this:

function query($name, $sql, $params, $db, $cache) {
    $result = $this->cache->get($name);

    if (!$result) {
        $stmt = $db->prepare($sql);
        $exec = $stmt->execute($params);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        $cache->add($name, $result);
    }

    return $result;
}
Ivo Sabev
yes, i was thinking in something more transparent (i dont want to name every query), i think i am going to hash the query concatenated with the rest of the params. what do u think?
Castro
Building a cache key from $sql + params is fairly simple -- just add this line to the top of Ivo's function, and remove the $name argument: `$name = 'querycache-' . md5(serialize(array($sql, $params)));`
Frank Farmer
+1  A: 

If you're just going to cache query results directly based on query string, Mysql's query cache already does this for you. Don't reinvent the wheel. The one potential difference is Mysql's query cache is aggressively invalidated so that stale (out of date, incorrect) data is never returned; depending on how you handle invalidation, your strategy may further reduce database load, but at the cost of serving stale, out of date data on a regular basis.

Additionally, you won't really be able to selectively expire your various cache keys when updates happen (how would you know which query strings should be expired when an insert/update runs?); as a result you'll just have to set a short expiration time (probably in seconds), to minimize the amount of time you're serving stale data. This will probably mean a low cache hit rate. In the end, the caching strategy you describe is simple to implement, but it's not very effective.

Make sure to read the "Generic Design Approaches" section of the memecached FAQ. A good caching strategy deletes/replaces cached data immediately when updates occur -- this allows you to cache data for hours/days/weeks, and simultaneously never serve out of date data to users.

Frank Farmer
You are right.My question makes no sense.Thanks!
Castro