<?php
class Cache_memcached {

	private static $_memcached;	// Holds the memcached object

		 		
	public function __construct($options=null)
	{
		self::memcached_connect();
	}
	
	public static function getInstance($options=null)
    {
		if(!(self::$_memcached instanceof self))
		{
            self::$_memcached	= new self($options);
        }
        return self::$_memcached;
    }	

	// ------------------------------------------------------------------------	
	
	/**
	 * Connect to memcached server.
	 */
	public function memcached_connect()
	{
		$this->_memcached	= new memcached();
		$this->_memcached->connect('127.0.0.1', 11211);
	}
	
	// ------------------------------------------------------------------------

	/**
	 * Set
	 *
	 * @param 	string		unique identifier
	 * @param 	mixed		data being cached
	 * @param 	int			time to live
	 * @return 	boolean 	true on success, false on failure
	 */
	public function set($id, $data, $ttl = 60)
	{
		$compress = FALSE;
		return $this->_memcached->set($id, $data, $compress, $ttl);
	}
	
	/**
	 * Fetch from cache
	 *
	 * @param 	mixed		unique key id
	 * @return 	mixed		data on success/false on failure
	 */	
	public function get($id)
	{	
		return $this->_memcached->get($id);
	}


	// ------------------------------------------------------------------------
	
	/**
	 * Delete from Cache
	 *
	 * @param 	mixed		key to be deleted.
	 * @return 	boolean 	true on success, false on failure
	 */
	public function delete($id)
	{
		return $this->_memcached->delete($id);
	}

	// ------------------------------------------------------------------------
	
	/**
	 * Clean the Cache
	 *
	 * @return 	boolean		false on failure/true on success
	 */
	public function clean()
	{
		return $this->_memcached->flush();
	}

	// ------------------------------------------------------------------------

	/**
	 * Cache Info
	 *
	 * @param 	null		type not supported in memcached
	 * @return 	mixed 		array on success, false on failure
	 */
	public function cache_info($type = NULL)
	{
		return $this->_memcached->getStats();
	}

	// ------------------------------------------------------------------------
	
	/**
	 * Get Cache Metadata
	 *
	 * @param 	mixed		key to get cache metadata on
	 * @return 	mixed		FALSE on failure, array on success.
	 */
	public function get_metadata($id)
	{
		$stored = $this->_memcached->get($id);

		if (count($stored) !== 3)
		{
			return FALSE;
		}

		list($data, $time, $ttl) = $stored;

		return array(
			'expire'	=> $time + $ttl,
			'mtime'		=> $time,
			'data'		=> $data
		);
	}

}
// End Class

/* End of file Cache_memcached.php */
/* Location: ./libraries/Cache/drivers/Cache_memcached.php */