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.
Example:
telnet ip port
stats
quit
After doing this I wanted to write a simple class to get the statistics of Memcache in PHP. Below is the Memcache Stats class I wrote to connect to a Memcache server and run a command.
class MemcacheStats {
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 = "$commandrn";
$out .= "quitrn";
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;
}
}