<?php
/**
* Created by PhpStorm.
* User: adv
* Date: 02.12.15
* Time: 19:19
*/
namespace Slivki\Util;
use Memcached;
use Symfony\Component\Config\Definition\Exception\Exception;
class SoftCache extends SoftCacheBase {
const CACHE_KEY_ALL = '-all-';
protected static $memcache;
//workaround
public static $serverAddress = 'memcache'; //TODO: move cache function to service
public function __construct($cacheKey) {
parent::__construct($cacheKey);
if (!static::$memcache) {
static::$memcache = new \Memcached();
static::$memcache->addServer(static::$serverAddress, 11211);
}
}
public function set($key, $object, $expire) {
if (!$object) {
$object = self::EMPTY_VALUE;
}
$result = static::$memcache->set($this->cacheKey . "-" . $key, $object, $expire);
if (!$result) {
$logger = Logger::instance('SoftCache');
$logger->info('setError: ' . static::$memcache->getResultMessage() . ' key=' . $key);
}
}
public function get($key, $default = null) {
try {
$object = static::$memcache->get($this->cacheKey . "-" . $key);
if ($object == self::EMPTY_VALUE) {
return null;
}
} catch (Exception $e) {
$logger = Logger::instance('SoftCache');
$logger->info('Exception in get ' . $key . ' ' . $e->getMessage());
$logger->info('Exception in get ' . $key . ' ' . static::$memcache->getResultMessage());
}
return $object;
}
public function setMulti($data, $expire) {
$prefixedList = [];
foreach ($data as $key=>$item) {
$prefixedList[$this->cacheKey . "-" . $key] = $item;
}
$result = static::$memcache->setMulti($prefixedList, $expire);
if (!$result) {
$logger = Logger::instance('SoftCache');
$logger->info('setError: ' . static::$memcache->getResultMessage());
}
}
public function getMulti(array $keys) {
$keys = array_unique($keys);
$prefixedKeys = array_map(function ($key) {
return $this->cacheKey . "-" . $key;
}, $keys);
$values = static::$memcache->getMulti($prefixedKeys, Memcached::GET_PRESERVE_ORDER);
if (!$values) {
return null;
}
$result = array_combine($keys, $values);
return $result;
}
public function add($key, $value, $expire) {
return static::$memcache->add($this->cacheKey . "-" . $key, $value, $expire);
}
public function delete($key) {
static::$memcache->delete($this->cacheKey . "-" . $key);
}
public function getAllKeys($subKey){
$keys = static::$memcache->getAllKeys();
if(!$keys){
return null;
}
$counters = [];
foreach ($keys as $key){
if(stristr($key, $subKey)){
$count = static::$memcache->get($key);
$explodeArray = explode('-visit-counter-', $key);
$counters[$explodeArray[1]] = $count;
}
}
return $counters;
}
public function increment($key) {
return static::$memcache->increment($this->cacheKey . "-" . $key);
}
}