Browse Source

Finished Cache class.

tags/2.0.0-beta
Qiang Xue 13 years ago
parent
commit
130d141709
  1. 154
      framework/caching/Cache.php
  2. 131
      framework/web/ThemeManager.php

154
framework/caching/Cache.php

@ -10,41 +10,30 @@
namespace yii\caching; namespace yii\caching;
use yii\base\ApplicationComponent; use yii\base\ApplicationComponent;
use yii\base\Exception;
/** /**
* Cache is the base class for cache classes with different cache storage implementation. * Cache is the base class for cache classes supporting different cache storage implementation.
* *
* A data item can be stored in cache by calling {@link set} and be retrieved back * A data item can be stored in cache by calling [[set()]] and be retrieved back
* later by {@link get}. In both operations, a key identifying the data item is required. * later (in the same or different request) by [[get()]]. In both operations,
* An expiration time and/or a dependency can also be specified when calling {@link set}. * a key identifying the data item is required. An expiration time and/or a [[CacheDependency|dependency]]
* If the data item expires or the dependency changes, calling {@link get} will not * can also be specified when calling [[set()]]. If the data item expires or the dependency
* return back the data item. * changes at the time of calling [[get()]], the cache will return no data.
* *
* Note, by definition, cache does not ensure the existence of a value * Derived classes should implement the following methods:
* even if it does not expire. Cache is not meant to be a persistent storage.
* *
* Cache implements the interface {@link ICache} with the following methods: * - [[getValue]]: retrieve the value with a key (if any) from cache
* <ul> * - [[setValue]]: store the value with a key into cache
* <li>{@link get} : retrieve the value with a key (if any) from cache</li> * - [[addValue]]: store the value only if the cache does not have this key before
* <li>{@link set} : store the value with a key into cache</li> * - [[deleteValue]]: delete the value with the specified key from cache
* <li>{@link add} : store the value only if cache does not have this key</li> * - [[flushValues]]: delete all values from cache
* <li>{@link delete} : delete the value with the specified key from cache</li>
* <li>{@link flush} : delete all values from cache</li>
* </ul>
* *
* Child classes must implement the following methods: * Because Cache implements the ArrayAccess interface, it can be used like an array. For example,
* <ul>
* <li>{@link getValue}</li>
* <li>{@link setValue}</li>
* <li>{@link addValue}</li>
* <li>{@link deleteValue}</li>
* <li>{@link flushValues} (optional)</li>
* <li>{@link serializeValue} (optional)</li>
* <li>{@link unserializeValue} (optional)</li>
* </ul>
* *
* Cache also implements ArrayAccess so that it can be used like an array. * ~~~
* $cache['foo'] = 'some data';
* echo $cache['foo'];
* ~~~
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
@ -52,18 +41,16 @@ use yii\base\Exception;
abstract class Cache extends ApplicationComponent implements \ArrayAccess abstract class Cache extends ApplicationComponent implements \ArrayAccess
{ {
/** /**
* @var string a string prefixed to every cache key so that it is unique. Defaults to null which means * @var string a string prefixed to every cache key so that it is unique. Defaults to null, meaning using
* to use the {@link CApplication::getId() application ID}. If different applications need to access the same * the value of [[Application::id]] as the key prefix. You may set this property to be an empty string
* pool of cached data, the same prefix should be set for each of the applications explicitly. * if you don't want to use key prefix. It is recommended that you explicitly set this property to some
* static value if the cached data needs to be shared among multiple applications.
*/ */
public $keyPrefix; public $keyPrefix;
/** /**
* @var boolean whether to hash the cache key for normalization purpose. Defaults to true. * @var boolean whether to hash the cache keys so that they can fit in the underlying cache storage.
* Setting this property to false makes sure the cache * Defaults to true. If you set this to be false, you have to make sure the cache keys are allowed by
* key will not be tampered when calling the relevant methods {@link get()}, {@link set()}, {@link add()} and {@link delete()}. This is useful if a Yii * the cache storage.
* application as well as an external application need to access the same cache pool (also see description of {@link keyPrefix} regarding this use case).
* However, without normalization you should make sure the affected cache backend does support the structure (charset, length, etc.) of all the provided
* cache keys, otherwise there might be unexpected behavior.
**/ **/
public $hashKey = true; public $hashKey = true;
/** /**
@ -90,6 +77,7 @@ abstract class Cache extends ApplicationComponent implements \ArrayAccess
} }
/** /**
* Generates a cache key from a given key.
* @param string $key a key identifying a value to be cached * @param string $key a key identifying a value to be cached
* @return string a key generated from the provided key which ensures the uniqueness across applications * @return string a key generated from the provided key which ensures the uniqueness across applications
*/ */
@ -123,9 +111,9 @@ abstract class Cache extends ApplicationComponent implements \ArrayAccess
/** /**
* Retrieves multiple values from cache with the specified keys. * Retrieves multiple values from cache with the specified keys.
* Some caches (such as memcache, apc) allow retrieving multiple cached values at one time, * Some caches (such as memcache, apc) allow retrieving multiple cached values at the same time,
* which may improve the performance since it reduces the communication cost. * which may improve the performance. In case a cache does not support this feature natively,
* In case a cache doesn't support this feature natively, it will be simulated by this method. * this method will try to simulate it.
* @param array $ids list of keys identifying the cached values * @param array $ids list of keys identifying the cached values
* @return array list of cached values corresponding to the specified keys. The array * @return array list of cached values corresponding to the specified keys. The array
* is returned in terms of (key,value) pairs. * is returned in terms of (key,value) pairs.
@ -160,13 +148,14 @@ abstract class Cache extends ApplicationComponent implements \ArrayAccess
/** /**
* Stores a value identified by a key into cache. * Stores a value identified by a key into cache.
* If the cache already contains such a key, the existing value and * If the cache already contains such a key, the existing value and
* expiration time will be replaced with the new ones. * expiration time will be replaced with the new ones, respectively.
* *
* @param string $id the key identifying the value to be cached * @param string $id the key identifying the value to be cached
* @param mixed $value the value to be cached * @param mixed $value the value to be cached
* @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire. * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
* @param CacheDependency $dependency dependency of the cached item. If the dependency changes, the item is labeled invalid. * @param CacheDependency $dependency dependency of the cached item. If the dependency changes,
* @return boolean true if the value is successfully stored into cache, false otherwise * the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
* @return boolean whether the value is successfully stored into cache
*/ */
public function set($id, $value, $expire = 0, $dependency = null) public function set($id, $value, $expire = 0, $dependency = null)
{ {
@ -187,8 +176,9 @@ abstract class Cache extends ApplicationComponent implements \ArrayAccess
* @param string $id the key identifying the value to be cached * @param string $id the key identifying the value to be cached
* @param mixed $value the value to be cached * @param mixed $value the value to be cached
* @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire. * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
* @param CacheDependency $dependency dependency of the cached item. If the dependency changes, the item is labeled invalid. * @param CacheDependency $dependency dependency of the cached item. If the dependency changes,
* @return boolean true if the value is successfully stored into cache, false otherwise * the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
* @return boolean whether the value is successfully stored into cache
*/ */
public function add($id, $value, $expire = 0, $dependency = null) public function add($id, $value, $expire = 0, $dependency = null)
{ {
@ -215,7 +205,7 @@ abstract class Cache extends ApplicationComponent implements \ArrayAccess
/** /**
* Deletes all values from cache. * Deletes all values from cache.
* Be careful of performing this operation if the cache is shared by multiple applications. * Be careful of performing this operation if the cache is shared among multiple applications.
* @return boolean whether the flush operation was successful. * @return boolean whether the flush operation was successful.
*/ */
public function flush() public function flush()
@ -226,68 +216,33 @@ abstract class Cache extends ApplicationComponent implements \ArrayAccess
/** /**
* Retrieves a value from cache with a specified key. * Retrieves a value from cache with a specified key.
* This method should be implemented by child classes to retrieve the data * This method should be implemented by child classes to retrieve the data
* from specific cache storage. The uniqueness and dependency are handled * from specific cache storage.
* in {@link get()} already. So only the implementation of data retrieval
* is needed.
* @param string $key a unique key identifying the cached value * @param string $key a unique key identifying the cached value
* @return string the value stored in cache, false if the value is not in the cache or expired. * @return string the value stored in cache, false if the value is not in the cache or expired.
*/ */
protected function getValue($key) abstract protected function getValue($key);
{
return false;
}
/**
* Retrieves multiple values from cache with the specified keys.
* The default implementation simply calls {@link getValue} multiple
* times to retrieve the cached values one by one.
* If the underlying cache storage supports multiget, this method should
* be overridden to exploit that feature.
* @param array $keys a list of keys identifying the cached values
* @return array a list of cached values indexed by the keys
*/
protected function getValues($keys)
{
$results = array();
foreach ($keys as $key) {
$results[$key] = $this->getValue($key);
}
return $results;
}
/** /**
* Stores a value identified by a key in cache. * Stores a value identified by a key in cache.
* This method should be implemented by child classes to store the data * This method should be implemented by child classes to store the data
* in specific cache storage. The uniqueness and dependency are handled * in specific cache storage.
* in {@link set()} already. So only the implementation of data storage
* is needed.
*
* @param string $key the key identifying the value to be cached * @param string $key the key identifying the value to be cached
* @param string $value the value to be cached * @param string $value the value to be cached
* @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire. * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
* @return boolean true if the value is successfully stored into cache, false otherwise * @return boolean true if the value is successfully stored into cache, false otherwise
*/ */
protected function setValue($key, $value, $expire) abstract protected function setValue($key, $value, $expire);
{
return true;
}
/** /**
* Stores a value identified by a key into cache if the cache does not contain this key. * Stores a value identified by a key into cache if the cache does not contain this key.
* This method should be implemented by child classes to store the data * This method should be implemented by child classes to store the data
* in specific cache storage. The uniqueness and dependency are handled * in specific cache storage.
* in {@link add()} already. So only the implementation of data storage
* is needed.
*
* @param string $key the key identifying the value to be cached * @param string $key the key identifying the value to be cached
* @param string $value the value to be cached * @param string $value the value to be cached
* @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire. * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
* @return boolean true if the value is successfully stored into cache, false otherwise * @return boolean true if the value is successfully stored into cache, false otherwise
*/ */
protected function addValue($key, $value, $expire) abstract protected function addValue($key, $value, $expire);
{
return true;
}
/** /**
* Deletes a value with the specified key from cache * Deletes a value with the specified key from cache
@ -295,19 +250,30 @@ abstract class Cache extends ApplicationComponent implements \ArrayAccess
* @param string $key the key of the value to be deleted * @param string $key the key of the value to be deleted
* @return boolean if no error happens during deletion * @return boolean if no error happens during deletion
*/ */
protected function deleteValue($key) abstract protected function deleteValue($key);
{
return true;
}
/** /**
* Deletes all values from cache. * Deletes all values from cache.
* Child classes may implement this method to realize the flush operation. * Child classes may implement this method to realize the flush operation.
* @return boolean whether the flush operation was successful. * @return boolean whether the flush operation was successful.
*/ */
protected function flushValues() abstract protected function flushValues();
/**
* Retrieves multiple values from cache with the specified keys.
* The default implementation calls [[getValue()]] multiple times to retrieve
* the cached values one by one. If the underlying cache storage supports multiget,
* this method should be overridden to exploit that feature.
* @param array $keys a list of keys identifying the cached values
* @return array a list of cached values indexed by the keys
*/
protected function getValues($keys)
{ {
return true; $results = array();
foreach ($keys as $key) {
$results[$key] = $this->getValue($key);
}
return $results;
} }
/** /**
@ -335,7 +301,7 @@ abstract class Cache extends ApplicationComponent implements \ArrayAccess
/** /**
* Stores the value identified by a key into cache. * Stores the value identified by a key into cache.
* If the cache already contains such a key, the existing value will be * If the cache already contains such a key, the existing value will be
* replaced with the new ones. To add expiration and dependencies, use the set() method. * replaced with the new ones. To add expiration and dependencies, use the [[set()]] method.
* This method is required by the interface ArrayAccess. * This method is required by the interface ArrayAccess.
* @param string $id the key identifying the value to be cached * @param string $id the key identifying the value to be cached
* @param mixed $value the value to be cached * @param mixed $value the value to be cached

131
framework/web/ThemeManager.php

@ -1,131 +0,0 @@
<?php
/**
* CThemeManager class file.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2011 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
/**
* CThemeManager manages the themes for the Web application.
*
* A theme is a collection of view/layout files and resource files
* (e.g. css, image, js files). When a theme is active, {@link CController}
* will look for the specified view/layout under the theme folder first.
* The corresponding view/layout files will be used if the theme provides them.
* Otherwise, the default view/layout files will be used.
*
* By default, each theme is organized as a directory whose name is the theme name.
* All themes are located under the "WebRootPath/themes" directory.
*
* To activate a theme, set the {@link CWebApplication::setTheme theme} property
* to be the name of that theme.
*
* Since a self-contained theme often contains resource files that are made
* Web accessible, please make sure the view/layout files are protected from Web access.
*
* @property array $themeNames List of available theme names.
* @property string $basePath The base path for all themes. Defaults to "WebRootPath/themes".
* @property string $baseUrl The base URL for all themes. Defaults to "/WebRoot/themes".
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @version $Id$
* @package system.web
* @since 1.0
*/
class CThemeManager extends CApplicationComponent
{
/**
* default themes base path
*/
const DEFAULT_BASEPATH='themes';
/**
* @var string the name of the theme class for representing a theme.
* Defaults to {@link CTheme}. This can also be a class name in dot syntax.
*/
public $themeClass='CTheme';
private $_basePath=null;
private $_baseUrl=null;
/**
* @param string $name name of the theme to be retrieved
* @return CTheme the theme retrieved. Null if the theme does not exist.
*/
public function getTheme($name)
{
$themePath=$this->getBasePath().DIRECTORY_SEPARATOR.$name;
if(is_dir($themePath))
{
$class=Yii::import($this->themeClass, true);
return new $class($name,$themePath,$this->getBaseUrl().'/'.$name);
}
else
return null;
}
/**
* @return array list of available theme names
*/
public function getThemeNames()
{
static $themes;
if($themes===null)
{
$themes=array();
$basePath=$this->getBasePath();
$folder=@opendir($basePath);
while(($file=@readdir($folder))!==false)
{
if($file!=='.' && $file!=='..' && $file!=='.svn' && $file!=='.gitignore' && is_dir($basePath.DIRECTORY_SEPARATOR.$file))
$themes[]=$file;
}
closedir($folder);
sort($themes);
}
return $themes;
}
/**
* @return string the base path for all themes. Defaults to "WebRootPath/themes".
*/
public function getBasePath()
{
if($this->_basePath===null)
$this->setBasePath(dirname(\Yii::$application->getRequest()->getScriptFile()).DIRECTORY_SEPARATOR.self::DEFAULT_BASEPATH);
return $this->_basePath;
}
/**
* @param string $value the base path for all themes.
* @throws CException if the base path does not exist
*/
public function setBasePath($value)
{
$this->_basePath=realpath($value);
if($this->_basePath===false || !is_dir($this->_basePath))
throw new CException(Yii::t('yii','Theme directory "{directory}" does not exist.',array('{directory}'=>$value)));
}
/**
* @return string the base URL for all themes. Defaults to "/WebRoot/themes".
*/
public function getBaseUrl()
{
if($this->_baseUrl===null)
$this->_baseUrl=\Yii::$application->getBaseUrl().'/'.self::DEFAULT_BASEPATH;
return $this->_baseUrl;
}
/**
* @param string $value the base URL for all themes.
*/
public function setBaseUrl($value)
{
$this->_baseUrl=rtrim($value,'/');
}
}
Loading…
Cancel
Save