<?php
/**
 * Web Application Component Toolkit
 *
 * @link http://www.phpwact.org/
 *
 * @author Wact Development Team
 * @link http://www.phpwact.org/team
 *
 * @copyright Copyright 2006, Jeff Moore
 * @license http://opensource.org/licenses/mit-license.php MIT
 */

/**
 * Adds a specific key prefix to all access to a cache, in effect
 * creating a namespace inside that cache.
 * Offers an example of how to extend the features of the cache with
 * a decorator.
 */
class Wact_Cache_Namespace implements Wact_Cache_Store {

    /**
     * The Cache we are wrapping
     *
     * @var Wact_Cache_Store
     */
    protected $cache;
    
    /**
     * The prefix to prepend to all keys
     *
     * @var string
     */
    protected $prefix;
    
    /**
     * A separator to use between the prefix and the actual key
     *
     * @var unknown_type
     */
    protected $separator;
    
    /**
     * Construct a namespace wrapper for a cache
     *
     * @param Wact_Cache_Store $cache The cache to wrap
     * @param string $prefix A key prefix to add to all calls
     * @param string $separator A separator to use between the prefix and key
     */
    function __construct(Wact_Cache_Store $cache, $prefix, $separator = '/') {
        $this->cache = $cache;
        $this->prefix = $prefix;
        $this->separator = $separator;
    }
    
    /**
     * Generate a new key based on an existing key
     *
     * @param string $key
     * @return string
     */
    protected function getKey($key) {
        return $this->prefix . $this->separator . $key;
    }
    
    /**
    * @see Wact_Cache_Store.store
    */
    public function store($key, $data, $lifetime = NULL) {
        return $this->cache->store($this->getKey($key), $data, $lifetime);
    }
    
    /**
    * @see Wact_Cache_Store.storeValue
    */
    public function storeValue($key, $data, $lifetime = NULL) {
        return $this->cache->storeValue($this->getKey($key), $data, $lifetime);
    }
    
    /**
    * @see Wact_Cache_Store.fetch
    */
    public function fetch($key, $default = NULL) {
        return $this->cache->fetch($this->getKey($key), $default);
    }

    /**
    * @see Wact_Cache_Store.fetchValue
    */
    public function fetchValue($key, $default = NULL) {
        return $this->cache->fetchValue($this->getKey($key), $default);
    }
    
    /**
    * @see Wact_Cache_Store.includeCode
    */
    public function includeCode($key) {
        return $this->cache->includeCode($this->getKey($key));
    }

    /**
    * @see Wact_Cache_Store.remove
    */
    public function remove($key) {
        return $this->cache->remove($this->getKey($key));
    }
    
    /**
    * @see Wact_Cache_Store.clear
    */
    public function clear() {
        return $this->cache->clear();
    }

}

?>