Memcache In PHP

Posted by Tully on Fri 22 October 2010

This week I have been doing a lot of caching with Memcache. Memcache is a great distributed memory caching system. I was running various tests and wanted to see general statistics. To check the stats for memcache, you can telnet into the Memcache ip/port and run the command stats.

$ telnet ip port  
stats  
quit

After doing this I wanted to write a quick PHP class to connect to a Memcache server and run commands.

<?php
class Memcache {

    private $ip;

    private $data;

    private $errors = array();

    public function __construct($ip)
    {
        $this->ip = $ip;
    }

    public function command($command)
    {
        try {
            $fh = @fsockopen($this->ip, 11211, $errno, $errstr, 30);
            if (!$fh) {
                array_push($this->errors, "$errno: $errstr");
                throw new Exception("Could not connect to memcache server at {$this->ip}");
            } else {
                $out = "$command\r\n";
                $out .= "quit\r\n";
                fwrite($fh, $out);
                while (!feof($fh)) {
                    $this->data .= fgets($fh, 128);
                }
            }
        } catch (Exception $e) {
            $this->errors = $e;
        }
        return $this->data;
    }

    public function isError()
    {
        if (!empty($this->errors)) {
            return $this->errors;
        }
        return false;
    }

    public function getData()
    {
        return $this->data;
    }
}