DEV Community

loading...

Simple Memcache In PHP

scottrobertson profile image Scott Robertson Originally published at blog.scottrobertson.me on ・1 min read

In the past year or so I have been using caching more and more. It has become a massive part of my job, and pretty much the whole site depends on it, and without it, things would start to fall over very quickly.

Here is a basic example of using Memcache in PHP:

$cache = new Memcache;
$cache->connect('127.0.0.1', 11211);

function getPosts()
{
    $cache_key = 'getPosts';
    $posts = $cache->get($cache_key);

    if ($posts === false) {
        $posts = DB::query('SELECT * FROM posts');
        $cache->set($cache_key, $posts);
    }

    return $posts;
}

Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide