2013-10-02 18:14:53 +02:00
|
|
|
<?php
|
|
|
|
namespace Rails\Cache\Store;
|
|
|
|
|
|
|
|
use Memcached;
|
|
|
|
use Rails;
|
|
|
|
|
|
|
|
class MemCachedStore extends AbstractStore
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* Instance of Memcached.
|
|
|
|
*/
|
|
|
|
private $connection;
|
|
|
|
|
|
|
|
public function __construct(array $servers)
|
|
|
|
{
|
|
|
|
if (!$servers)
|
|
|
|
$servers = [['localhost', 11211]];
|
|
|
|
|
|
|
|
$this->connection = new Memcached('Rails.Application.' . Rails::application()->name());
|
|
|
|
$this->connection->addServers($servers);
|
|
|
|
}
|
|
|
|
|
|
|
|
public function connection()
|
|
|
|
{
|
|
|
|
return $this->connection;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function read($key, array $params = [])
|
|
|
|
{
|
|
|
|
$value = $this->connection->get($key);
|
|
|
|
|
2013-10-21 10:07:58 +02:00
|
|
|
if ($value === false) {
|
2013-10-02 18:14:53 +02:00
|
|
|
if ($this->connection->getResultCode() == Memcached::RES_NOTFOUND) {
|
|
|
|
return null;
|
|
|
|
} else {
|
|
|
|
# There was some kind of error.
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return unserialize($value);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public function write($key, $val, array $params)
|
|
|
|
{
|
|
|
|
$val = serialize($val);
|
|
|
|
|
|
|
|
if (isset($params['expires_in'])) {
|
|
|
|
if (!ctype_digit((string)$params['expires_in']))
|
|
|
|
$expires_in = strtotime('+' . $params['expires_in']);
|
2013-10-21 10:07:58 +02:00
|
|
|
} else {
|
2013-10-02 18:14:53 +02:00
|
|
|
$expires_in = 0;
|
2013-10-21 10:07:58 +02:00
|
|
|
}
|
2013-10-02 18:14:53 +02:00
|
|
|
|
2013-10-21 10:07:58 +02:00
|
|
|
return $this->connection->set($key, $val, $expires_in);
|
2013-10-02 18:14:53 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
public function delete($key, array $params)
|
|
|
|
{
|
|
|
|
$time = !empty($params['time']) ? $params['time'] : 0;
|
|
|
|
return $this->connection->delete($key, $time);
|
|
|
|
}
|
|
|
|
|
|
|
|
public function exists($key, array $params)
|
|
|
|
{
|
|
|
|
if ($this->connection->get($key))
|
|
|
|
return true;
|
|
|
|
else {
|
|
|
|
# An error could have occured.
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|