Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 16985 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

<?php

declare(strict_types=1);

namespace LeadersLinked\Cache;


class CacheImpl implements CacheInterface
{
    
    /**
     * 
     * @var \LeadersLinked\Cache\CacheInterface
     */
    private static $_instance;
    
    
    /**
     * 
     * @var \Memcached
     */
    private $cache;
    
    /**
     * 
     * @var int
     */
    private $ttl;

    
    /**
     *
     * @param Array $config
     */
    private function __construct($config)
    {
  
         $this->ttl         = intval($config['leaderslinked.memcache.ttl'], 10);
         $host              = strval($config['leaderslinked.memcache.host']);
         $port              = intval($config['leaderslinked.memcache.port'], 10);
         

         $this->cache = new \Memcached();
         $this->cache->addserver($host, $port);
         
        
        
    }
    
    /**
     * 
     * @param array $config
     * @return \LeadersLinked\Cache\CacheInterface
     */
    public static function getInstance($config)
    {
        if(self::$_instance == null) {
            self::$_instance = new CacheImpl($config);
        }
        return self::$_instance;
    }
    
    /**
     *
     * @param string $key
     * @param mixed $value
     */
    public function setItem($key, $value)
    {
        
        if($this->cache->checkKey($key)) {
            
            $this->cache->replace($key, serialize($value), $this->ttl);
        } else {
            $this->cache->add($key, serialize($value), $this->ttl);
        }
     
  
    }
    
  
    
    /**
     *
     * @param string $key
     * @return boolean
     */
    public function removeItem($key)
    {
        if($this->cache->checkKey($key)) {
            return $this->cache->delete($key);
        } else {
            return true;
        }
    }
    
    
    
    
    
    /**
     *
     * @param string $key
     * @return boolean
     */
    public function hasItem($key)
    {
        return $this->cache->checkKey($key);
        
    }
    
    
    /**
     *
     * @param string $key
     * @return mixed
     */
    public function getItem($key)
    {
        if($this->cache->checkKey($key)) {
            $value = $this->cache->get($key);
            if(is_string($value)) {
                return unserialize($value);
            } else {
                return $value;
            }
        } else {
            return null;
        }
        
    }
    


}