<?php
/**
 * @copyright NetMonsters <team@netmonsters.ru>
 * @link http://netmonsters.ru
 * @package Majestic
 * @subpackage Cache
 * @since 2010-03-04
 * @version SVN: $Id$
 * @filesource $URL$
 */

class MemcacheCache extends Cache
{
    
    /**
     * @var Memcache
     */
    protected $connection = null;
    
    public function __construct($config)
    {
        $this->connection = new Memcache();
        
        $required = array('hostname', 'port');
        foreach ($config as $c) {
            foreach ($required as $option) {
                if (!isset($c[$option])) {
                    throw new Exception('Configuration must have a "' . $option . '".');
                }
            }
            $this->connection->addServer($c['hostname'], $c['port']);
        }
    }
    
    /**
     * Add an item to the cache
     * 
     * @param string $key
     * @param mixed $value
     * @param int $expire
     * @return bool
     */
    public function add($key, $value, $expire = 0)
    {
        return $this->connection->add($key, $value, null, $expire);
    }
    
    /**
     * Decrement item's value
     * 
     * @param string $key
     * @param int $decrement
     * @return bool
     */
    public function decrement($key, $decrement = 1)
    {
        return $this->connection->decrement($key, $decrement);
    }
    
    /**
     * Delete item from the cache
     * 
     * @param string $key
     * @param int $value
     * @return bool
     */
    public function del($key)
    {
        return $this->connection->delete($key);
    }
    
    /**
     * Flush all existing items
     * 
     * @return bool
     */
    public function flush()
    {
        return $this->connection->flush();
    }
    
    /**
     * Retrieve item from the cache
     * 
     * @param mixed $key
     * @return mixed
     */
    public function get($key)
    {
        return $this->connection->get($key);
    }
    
    /**
     * Increment item's value
     * 
     * @param string $key
     * @param int $increment
     * @return bool
     */
    public function increment($key, $increment = 1)
    {
        return $this->connection->increment($key, $increment);
    }
    
    /**
     * Replace value of the existing item
     * 
     * @param string $key
     * @param mixed $var
     * @param int $expire
     * @return bool
     */
    public function replace($key, $value, $expire = 0)
    {
        return $this->connection->replace($key, $value, null, $expire);
    }
    
    /**
     * Store data in the cache
     * 
     * @param string $key
     * @param mixed $value
     * @param int $expire
     * @return bool
     */
    public function set($key, $value, $expire = 0)
    {
        return $this->connection->set($key, $value, null, $expire);
    }
}