phpmysqlwordpressmemcachedxcache

Memcached/XCache caching of SQL results?


I just designed an admin console for a social networking website. My boss now wants me to cache the results of several MySQL queries that build these results (for 24 hours). The site uses Memcached (with Wordpress W3 total cache) and XCache. I wanted to know what's the best way to do this.

Here is an example of one such query and how I am getting the results (basically I am returning aggregate stats on users, which means my results are fairly simple, eg:

//users who registered in last 365 days
$users_reg_365 = "select ID
from wp_users
where user_registered > NOW() - interval 365 day";

then use the wpdb query class to get the results:

$users_reg_365 = $wpdb->get_results($users_reg_365);

then display the result in the dashboard:

<li><?php echo "Total users who registered within last 365 days: <span class='sqlresult'>" . sizeof($users_reg_365) . "</span>"; ?></li>

My understanding of Memcached/XCache is that it basically stores strings, so would it make sense to just cache sizeof($users_reg_365)?

The last wrinkle is that our Wordpress site uses W3 total cache, which leverages Memcached, and the boss asked me not to use Memcached but XCache instead, but I find the docs a bit confusing. What's the best way to solve this problem? Can SQL itself be told to 'remember' certain queries like this, or is memory caching the way to go?

Thanks!


Solution

  • You can find more about the differences of both here: Difference between Memcache, APC, XCache and other alternatives I've not heard of

    An example how you could

    <?php
    $m = new Memcached();
    $m->addServer('localhost', 11211);
    
    // cache 24hrs
    $cache_expire = 86400;
    
    
    // users is your key
    $users_reg_365 = $m->get('users_reg_365');
    if (empty($users_reg_365)) {
        $users_reg_365 = "select ID from wp_users where user_registered > NOW() - interval 365 day";
        $m->set('users_reg_365', $cache_expire);
    }
    

    If you need to exactly refresh the cache at middle night change the value of $cache_expire.

    You can refer to the full reference of memcached at http://www.php.net/manual/en/memcached.get.php