Example code
Converting a database or object creation queries to use memcached is simple. Typically, when using straight database queries, example code would be as follows:
function get_foo (int userid) { result = db_select("SELECT * FROM users WHERE userid = ?", userid); return result; }
After conversion to memcached, the same call might look like the following
function get_foo (int userid) { result = memcached_fetch("userrow:" + userid); if (!result) { result = db_select("SELECT * FROM users WHERE userid = ?", userid); memcached_add("userrow:" + userid, result); } return result; }
The server would first check whether a memcached value with the unique key "userrow:userid" exists, where userid is some number. If the result does not exist, it would select from the database as usual, and set the unique key using the memcached API add function call.
However, if only this API call were modified, the server would end up fetching incorrect data following any database update actions: the memcached "view" of the data would become out of date. Therefore, in addition to creating an "add" call, an update call would be also needed, using the memcached set function.
function update_foo(int userid, string dbUpdateString) { result = db_execute(dbUpdateString); if (result) { data = createUserDataFromDBString(dbUpdateString); memcached_set("userrow:" + userid, data); } }