Commit 0c85d56b by Qiang Xue

finished view.

parent 2746b6ed
...@@ -7,6 +7,8 @@ ...@@ -7,6 +7,8 @@
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
use yii\base\Exception;
/** /**
* Gets the application start timestamp. * Gets the application start timestamp.
*/ */
...@@ -126,7 +128,7 @@ class YiiBase ...@@ -126,7 +128,7 @@ class YiiBase
* will be included only when the class is being used. This parameter is used only when * will be included only when the class is being used. This parameter is used only when
* the path alias refers to a class. * the path alias refers to a class.
* @return string the class name or the directory that this alias refers to * @return string the class name or the directory that this alias refers to
* @throws \yii\base\Exception if the path alias is invalid * @throws Exception if the path alias is invalid
*/ */
public static function import($alias, $forceInclude = false) public static function import($alias, $forceInclude = false)
{ {
...@@ -153,7 +155,7 @@ class YiiBase ...@@ -153,7 +155,7 @@ class YiiBase
} }
if (($path = static::getAlias(dirname($alias))) === false) { if (($path = static::getAlias(dirname($alias))) === false) {
throw new \yii\base\Exception('Invalid path alias: ' . $alias); throw new Exception('Invalid path alias: ' . $alias);
} }
if ($isClass) { if ($isClass) {
...@@ -184,10 +186,12 @@ class YiiBase ...@@ -184,10 +186,12 @@ class YiiBase
* *
* Note, this method does not ensure the existence of the resulting path. * Note, this method does not ensure the existence of the resulting path.
* @param string $alias alias * @param string $alias alias
* @return mixed path corresponding to the alias, false if the root alias is not previously registered. * @param boolean $throwException whether to throw exception if the alias is invalid.
* @return string|boolean path corresponding to the alias, false if the root alias is not previously registered.
* @throws Exception if the alias is invalid and $throwException is true.
* @see setAlias * @see setAlias
*/ */
public static function getAlias($alias) public static function getAlias($alias, $throwException = false)
{ {
if (isset(self::$aliases[$alias])) { if (isset(self::$aliases[$alias])) {
return self::$aliases[$alias]; return self::$aliases[$alias];
...@@ -199,7 +203,11 @@ class YiiBase ...@@ -199,7 +203,11 @@ class YiiBase
return self::$aliases[$alias] = self::$aliases[$rootAlias] . substr($alias, $pos); return self::$aliases[$alias] = self::$aliases[$rootAlias] . substr($alias, $pos);
} }
} }
return false; if ($throwException) {
throw new Exception("Invalid path alias: $alias");
} else {
return false;
}
} }
/** /**
...@@ -218,7 +226,7 @@ class YiiBase ...@@ -218,7 +226,7 @@ class YiiBase
* - a URL (e.g. `http://www.yiiframework.com`) * - a URL (e.g. `http://www.yiiframework.com`)
* - a path alias (e.g. `@yii/base`). In this case, the path alias will be converted into the * - a path alias (e.g. `@yii/base`). In this case, the path alias will be converted into the
* actual path first by calling [[getAlias]]. * actual path first by calling [[getAlias]].
* @throws \yii\base\Exception if $path is an invalid alias * @throws Exception if $path is an invalid alias
* @see getAlias * @see getAlias
*/ */
public static function setAlias($alias, $path) public static function setAlias($alias, $path)
...@@ -230,7 +238,7 @@ class YiiBase ...@@ -230,7 +238,7 @@ class YiiBase
} elseif (($p = static::getAlias($path)) !== false) { } elseif (($p = static::getAlias($path)) !== false) {
self::$aliases[$alias] = $p; self::$aliases[$alias] = $p;
} else { } else {
throw new \yii\base\Exception('Invalid path: ' . $path); throw new Exception('Invalid path: ' . $path);
} }
} }
...@@ -291,7 +299,7 @@ class YiiBase ...@@ -291,7 +299,7 @@ class YiiBase
include($classFile); include($classFile);
return true; return true;
} else { } else {
throw new \yii\base\Exception("Class name '$className' does not match the class file '" . realpath($classFile) . "'. Have you checked their case sensitivity?"); throw new Exception("Class name '$className' does not match the class file '" . realpath($classFile) . "'. Have you checked their case sensitivity?");
} }
} }
...@@ -339,7 +347,7 @@ class YiiBase ...@@ -339,7 +347,7 @@ class YiiBase
* *
* @param string|array $config the configuration. It can be either a string or an array. * @param string|array $config the configuration. It can be either a string or an array.
* @return mixed the created object * @return mixed the created object
* @throws \yii\base\Exception if the configuration is invalid. * @throws Exception if the configuration is invalid.
* @see \yii\base\Object::newInstance() * @see \yii\base\Object::newInstance()
*/ */
public static function createObject($config) public static function createObject($config)
...@@ -351,7 +359,7 @@ class YiiBase ...@@ -351,7 +359,7 @@ class YiiBase
$class = $config['class']; $class = $config['class'];
unset($config['class']); unset($config['class']);
} else { } else {
throw new \yii\base\Exception('Object configuration must be an array containing a "class" element.'); throw new Exception('Object configuration must be an array containing a "class" element.');
} }
if (!class_exists($class, false)) { if (!class_exists($class, false)) {
......
...@@ -70,9 +70,12 @@ class Controller extends Component implements Initable ...@@ -70,9 +70,12 @@ class Controller extends Component implements Initable
*/ */
public $action; public $action;
/** /**
* @var View the view currently being used * @var string|boolean the name of the layout to be applied to this controller's views.
* This property mainly affects the behavior of [[render()]].
* Defaults to null, meaning the layout specified by the [[module]] should be used.
* If false, no layout will be applied.
*/ */
private $_view; public $layout;
/** /**
* @param string $id ID of this controller * @param string $id ID of this controller
...@@ -295,66 +298,39 @@ class Controller extends Component implements Initable ...@@ -295,66 +298,39 @@ class Controller extends Component implements Initable
/** /**
* This method is invoked right after an action renders its result using [[render()]]. * This method is invoked right after an action renders its result using [[render()]].
* @param string $view the view just rendered * @param string $view the view just rendered
* @param string $content the content to be displayed
* @return string the content to be displayed. This may be the same as the input content or the one
* modified by event handlers.
*/ */
public function afterRender($view) public function afterRender($view, $content)
{ {
$this->trigger(__METHOD__, new RenderEvent($view)); $event = new RenderEvent($view, $content);
$this->trigger(__METHOD__, $event);
return $event->content;
} }
public function render($view, $params = array()) public function render($view, $params = array())
{ {
if ($this->beforeRender($view)) { if ($this->beforeRender($view)) {
$v = $this->createView(); $content = $this->createView()->render($view, $params);
if (($theme = \Yii::$application->getTheme()) !== null) { $content = $this->afterRender($view, $content);
$v->basePath[] = $theme->getViewPath($this); return $content;
$v->rootPath[] = $theme->getViewPath();
}
$v->basePath[] = $this->getViewPath();
$v->rootPath[] = \Yii::$application->getViewPath();
$v->render($view, $params);
$this->afterRender($view);
} }
return '';
} }
public function renderText($text) public function renderText($text)
{ {
return $this->createView()->renderText($text);
} }
public function renderPartial($view, $params = array()) public function renderPartial($view, $params = array())
{ {
return $this->createView()->renderPartial($view, $params);
}
public function resolveLayout()
{
$layout = $this->layout;
$module = $this->module;
while ($layout === null && $module !== null) {
$layout = $module->layout;
$module = $module->module;
$layout = $
}
}
public function getView()
{
if ($this->_view === null) {
$this->_view = $this->createView();
$this->_view->owner = $this;
if (($theme = \Yii::$application->getTheme()) !== null) {
$this->_view->basePath[] = $theme->getViewPath($this);
$this->_view->rootPath[] = $theme->getViewPath();
}
$this->_view->basePath[] = $this->getViewPath();
$this->_view->rootPath[] = \Yii::$application->getViewPath();
}
return $this->_view;
} }
public function createView() public function createView()
{ {
return new View; return new View($this);
} }
} }
...@@ -319,7 +319,7 @@ class ErrorHandler extends ApplicationComponent ...@@ -319,7 +319,7 @@ class ErrorHandler extends ApplicationComponent
public function renderAsHtml($exception) public function renderAsHtml($exception)
{ {
$view = new View; $view = new View;
$view->owner = $this; $view->context = $this;
$name = !YII_DEBUG || $exception instanceof HttpException ? $this->errorView : $this->exceptionView; $name = !YII_DEBUG || $exception instanceof HttpException ? $this->errorView : $this->exceptionView;
echo $view->render($name, array( echo $view->render($name, array(
'exception' => $exception, 'exception' => $exception,
......
...@@ -24,6 +24,10 @@ class RenderEvent extends Event ...@@ -24,6 +24,10 @@ class RenderEvent extends Event
*/ */
public $view; public $view;
/** /**
* @var string the content to be displayed
*/
public $content;
/**
* @var boolean whether the action is in valid state and its life cycle should proceed. * @var boolean whether the action is in valid state and its life cycle should proceed.
*/ */
public $isValid = true; public $isValid = true;
......
...@@ -23,90 +23,39 @@ class Theme extends ApplicationComponent ...@@ -23,90 +23,39 @@ class Theme extends ApplicationComponent
public function init() public function init()
{ {
if ($this->basePath !== null) { if ($this->basePath !== null) {
$this->basePath = \Yii::getAlias($this->basePath); $this->basePath = \Yii::getAlias($this->basePath, true);
} else { } else {
throw new Exception("Theme.basePath must be set."); throw new Exception("Theme.basePath must be set.");
} }
if ($this->baseUrl !== null) { if ($this->baseUrl !== null) {
$this->baseUrl = \Yii::getAlias($this->baseUrl); $this->baseUrl = \Yii::getAlias($this->baseUrl, true);
} else { } else {
throw new Exception("Theme.baseUrl must be set."); throw new Exception("Theme.baseUrl must be set.");
} }
} }
/** /**
* @param Controller $controller * @param Application|Module|Controller|Object $context
* @return string * @return string
*/ */
public function getViewPath($controller = null) public function getViewPath($context = null)
{ {
$path = $this->basePath . DIRECTORY_SEPARATOR . 'views'; $viewPath = $this->basePath . DIRECTORY_SEPARATOR . 'views';
return $controller === null ? $path : $path . DIRECTORY_SEPARATOR . $controller->id; if ($context === null || $context instanceof Application) {
} return $viewPath;
} elseif ($context instanceof Controller || $context instanceof Module) {
public function getLayoutPath($module = null) return $viewPath . DIRECTORY_SEPARATOR . $context->getUniqueId();
{ } else {
$path = $this->getViewPath($module); return $viewPath . DIRECTORY_SEPARATOR . str_replace('\\', '_', get_class($context));
return $controller === null ? $path : $path . DIRECTORY_SEPARATOR . $controller->id; }
}
public function getWidgetViewPath($widget)
{
}
/**
* @return string the path for controller views. Defaults to 'ThemeRoot/views'.
*/
public function getViewPath()
{
return $this->_basePath . DIRECTORY_SEPARATOR . 'views';
}
/**
* Finds the view file for the specified controller's view.
* @param CController $controller the controller
* @param string $viewName the view name
* @return string the view file path. False if the file does not exist.
*/
public function getViewFile($controller, $viewName)
{
$moduleViewPath = $this->getViewPath();
if (($module = $controller->getModule()) !== null)
{
$moduleViewPath .= '/' . $module->getId();
}
return $controller->resolveViewFile($viewName, $this->getViewPath() . '/' . $controller->getUniqueId(), $this->getViewPath(), $moduleViewPath);
} }
/** /**
* Finds the layout file for the specified controller's layout. * @param Module $module
* @param CController $controller the controller * @return string
* @param string $layoutName the layout name
* @return string the layout file path. False if the file does not exist.
*/ */
public function getLayoutFile($controller, $layoutName) public function getLayoutPath($module = null)
{ {
$moduleViewPath = $basePath = $this->getViewPath(); return $this->getViewPath($module) . DIRECTORY_SEPARATOR . 'layouts';
$module = $controller->getModule();
if (empty($layoutName)) {
while ($module !== null) {
if ($module->layout === false)
return false;
if (!empty($module->layout))
break;
$module = $module->getParentModule();
}
if ($module === null)
$layoutName = Yii::app()->layout;
else {
$layoutName = $module->layout;
$moduleViewPath .= '/' . $module->getId();
}
}
else if ($module !== null)
$moduleViewPath .= '/' . $module->getId();
return $controller->resolveViewFile($layoutName, $moduleViewPath . '/layouts', $basePath, $moduleViewPath);
} }
} }
...@@ -10,6 +10,7 @@ ...@@ -10,6 +10,7 @@
namespace yii\base; namespace yii\base;
use yii\util\FileHelper; use yii\util\FileHelper;
use yii\base\Application;
/** /**
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
...@@ -18,26 +19,18 @@ use yii\util\FileHelper; ...@@ -18,26 +19,18 @@ use yii\util\FileHelper;
class View extends Component class View extends Component
{ {
/** /**
* @var Object the owner of this view * @var Controller|Widget|Object the context under which this view is being rendered
*/ */
public $owner; public $context;
/** /**
* @var string|array the directories where the view file should be looked for a *relative* view name is given. * @var string|array the directories where the view file should be looked for when a *relative* view name is given.
* This can be either a string representing a single directory, or an array representing multiple directories. * This can be either a string representing a single directory, or an array representing multiple directories.
* If the latter, the view file will be looked for in the given directories in the order they are specified. * If the latter, the view file will be looked for in the directories in the order they are specified.
* Path aliases can be used. This property must be set before calling [[render()]] with a relative view name. * Path aliases can be used. If this property is not set, relative view names should be treated as absolute ones.
* @see roothPath * @see roothPath
*/ */
public $basePath; public $basePath;
/** /**
* @var string|array the directories where the view file should be looked for an *absolute* view name is given.
* This can be either a string representing a single directory, or an array representing multiple directories.
* If the latter, the view file will be looked for in the given directories in the order they are specified.
* Path aliases can be used. This property must be set before calling [[render()]] with an absolute view name.
* @see basePath
*/
public $rootPath;
/**
* @var string the language that the view should be rendered in. If not set, it will use * @var string the language that the view should be rendered in. If not set, it will use
* the value of [[Application::language]]. * the value of [[Application::language]].
*/ */
...@@ -48,11 +41,47 @@ class View extends Component ...@@ -48,11 +41,47 @@ class View extends Component
*/ */
public $sourceLanguage; public $sourceLanguage;
/** /**
* @var boolean whether to localize the view when possible. Defaults to true.
* Note that when this is true, if a localized view cannot be found, the original view will be rendered.
* No error will be reported.
*/
public $localizeView = true;
/**
* @var boolean whether to theme the view when possible. Defaults to true.
* Note that theming will be disabled if [[Application::theme]] is null.
*/
public $themeView = true;
/**
* @var mixed custom parameters that are available in the view template * @var mixed custom parameters that are available in the view template
*/ */
public $params; public $params;
/** /**
* Constructor.
* @param Controller|Widget|Object $context the context under which this view is being rendered (e.g. controller, widget)
*/
public function __construct($context = null)
{
$this->context = $context;
}
public function render($view, $params = array())
{
$content = $this->renderPartial($view, $params);
return $this->renderText($content);
}
public function renderText($text)
{
$layoutFile = $this->findLayoutFile();
if ($layoutFile !== false) {
return $this->renderFile($layoutFile, array('content' => $text));
} else {
return $text;
}
}
/**
* Renders a view. * Renders a view.
* *
* The method first finds the actual view file corresponding to the specified view. * The method first finds the actual view file corresponding to the specified view.
...@@ -72,7 +101,7 @@ class View extends Component ...@@ -72,7 +101,7 @@ class View extends Component
* @return string the rendering result * @return string the rendering result
* @throws Exception if the view file cannot be found * @throws Exception if the view file cannot be found
*/ */
public function render($view, $params = array()) public function renderPartial($view, $params = array())
{ {
$file = $this->findViewFile($view); $file = $this->findViewFile($view);
if ($file !== false) { if ($file !== false) {
...@@ -96,7 +125,7 @@ class View extends Component ...@@ -96,7 +125,7 @@ class View extends Component
public function createWidget($class, $properties = array()) public function createWidget($class, $properties = array())
{ {
$properties['class'] = $class; $properties['class'] = $class;
return \Yii::createObject($properties, $this->owner); return \Yii::createObject($properties, $this->context);
} }
public function widget($class, $properties = array()) public function widget($class, $properties = array())
...@@ -156,7 +185,6 @@ class View extends Component ...@@ -156,7 +185,6 @@ class View extends Component
/** /**
* Ends recording a clip. * Ends recording a clip.
* This method is an alias to {@link endWidget}.
*/ */
public function endClip() public function endClip()
{ {
...@@ -262,35 +290,165 @@ class View extends Component ...@@ -262,35 +290,165 @@ class View extends Component
if (($extension = FileHelper::getExtension($view)) === '') { if (($extension = FileHelper::getExtension($view)) === '') {
$view .= '.php'; $view .= '.php';
} }
if ($view[0] === '@') { if (strncmp($view, '@', 1) === 0) {
$file = \Yii::getAlias($view); $file = \Yii::getAlias($view);
if ($file === false) { } elseif (strncmp($view, '/', 1) !== 0) {
return false; $file = $this->findRelativeViewFile($view);
} else {
$file = $this->findAbsoluteViewFile($view);
}
if ($file === false || !is_file($file)) {
return false;
} elseif ($this->localizeView) {
return FileHelper::localize($file, $this->language, $this->sourceLanguage);
} else {
return $file;
}
}
/**
* Finds the view file corresponding to the given relative view name.
* The method will look for the view file under a set of directories returned by [[resolveBasePath()]].
* If no base path is given, the view will be treated as an absolute view and the result of
* [[findAbsoluteViewFile()]] will be returned.
* @param string $view the relative view name
* @return string|boolean the view file path, or false if the view file cannot be found
*/
protected function findRelativeViewFile($view)
{
$paths = $this->resolveBasePath();
if ($paths === array()) {
return $this->findAbsoluteViewFile($view);
}
if ($this->themeView && $this->context !== null && ($theme = \Yii::$application->getTheme()) !== null) {
array_unshift($paths, $theme->getViewPath($this->context));
}
foreach ($paths as $path) {
$file = \Yii::getAlias($path . '/' . $view);
if ($file !== false && is_file($file)) {
return $file;
}
}
return $paths === array() ? $this->findAbsoluteViewFile($view) : false;
}
/**
* Finds the view file corresponding to the given absolute view name.
* If the view name starts with double slashes `//`, the method will look for the view file
* under [[Application::getViewPath()]]. Otherwise, it will look for the view file under the
* view path of the currently active module.
* @param string $view the absolute view name
* @return string|boolean the view file path, or false if the view file cannot be found
*/
protected function findAbsoluteViewFile($view)
{
$app = \Yii::$application;
if (strncmp($view, '//', 2) !== 0 && $app->controller !== null) {
$module = $app->controller->module;
} else {
$module = $app;
}
if ($this->themeView && ($theme = $app->getTheme()) !== null) {
$paths[] = $theme->getViewPath($module);
}
$paths[] = $module->getViewPath();
$view = ltrim($view, '/');
foreach ($paths as $path) {
$file = \Yii::getAlias($path . '/' . $view);
if ($file !== false && is_file($file)) {
return $file;
} }
}
return false;
}
/**
* Resolves the base paths that will be used to determine view files for relative view names.
* The method resolves the base path using the following algorithm:
*
* - If [[basePath]] is not empty, it is returned;
* - If [[context]] is a controller, it will return the subdirectory named as
* [[Controller::uniqueId]] under the controller's module view path;
* - If [[context]] is an object, it will return the `views` subdirectory under
* the directory containing the object class file.
* - Otherwise, it will return false.
* @return array the base paths
*/
protected function resolveBasePath()
{
if (!empty($this->basePath)) {
return is_array($this->basePath) ? $this->basePath : array($this->basePath);
} elseif ($this->context instanceof Controller) {
return $this->context->module->getViewPath() . '/' . $this->context->getUniqueId();
} elseif ($this->context !== null) {
$class = new \ReflectionClass($this->context);
return array(dirname($class->getFileName()) . '/views');
} else { } else {
if ($view[0] === '/') { return array();
$paths = $this->rootPath; }
$view = substr($view, 1); }
} else {
$paths = $this->basePath; /**
* Finds the layout file for the current [[context]].
* The method will return false if [[context]] is not a controller.
* When [[context]] is a controller, the following algorithm is used to determine the layout file:
*
* - If `context.layout` is false, it will return false;
* - If `context.layout` is a string, it will look for the layout file under the [[Module::layoutPath|layout path]]
* of the controller's parent module;
* - If `context.layout` is null, the following steps are taken to resolve the actual layout to be returned:
* * Check the `layout` property of the parent module. If it is null, check the grand parent module and so on
* until a non-null layout is encountered. Let's call this module the *effective module*.
* * If the layout is null or false, it will return false;
* * Otherwise, it will look for the layout file under the layout path of the effective module.
*
* The themed layout file will be returned if theme is enabled and the theme contains such a layout file.
*
* @return string|boolean the layout file path, or false if the context does not need layout.
* @throws Exception if the layout file cannot be found
*/
public function findLayoutFile()
{
if (!$this->context instanceof Controller || $this->context->layout === false) {
return false;
}
$module = $this->context->module;
while ($module !== null && $module->layout === null) {
$module = $module->module;
}
if ($module === null || $module->layout === null || $module->layout === false) {
return false;
}
$view = $module->layout;
if (($extension = FileHelper::getExtension($view)) === '') {
$view .= '.php';
}
if (strncmp($view, '@', 1) === 0) {
$file = \Yii::getAlias($view);
} elseif (strncmp($view, '/', 1) === 0) {
$file = $this->findAbsoluteViewFile($view);
} else {
if ($this->themeView && ($theme = \Yii::$application->getTheme()) !== null) {
$paths[] = $theme->getLayoutPath($module);
} }
if (!empty($paths)) { $paths[] = $module->getLayoutPath();
if (!is_array($paths)) { $file = false;
$paths = array($paths); foreach ($paths as $path) {
} $f = \Yii::getAlias($path . '/' . $view);
foreach ($paths as $path) { if ($f !== false && is_file($f)) {
$file = \Yii::getAlias($path . '/' . $view); $file = $f;
if (is_file($file)) { break;
break;
}
} }
} }
} }
if (isset($file) && is_file($file)) { if ($file === false || !is_file($file)) {
$file = FileHelper::localize($file, $this->language, $this->sourceLanguage); throw new Exception("Unable to find the layout file for layout '{$module->layout}' (specified by " . get_class($module) . ")");
return is_file($file) ? $file : false; } elseif ($this->localizeView) {
return FileHelper::localize($file, $this->language, $this->sourceLanguage);
} else { } else {
return false; return $file;
} }
} }
} }
\ No newline at end of file
...@@ -98,7 +98,7 @@ class Widget extends Component implements Initable ...@@ -98,7 +98,7 @@ class Widget extends Component implements Initable
*/ */
public function render($view, $params = array()) public function render($view, $params = array())
{ {
return $this->createView()->render($view, $params); return $this->createView()->renderPartial($view, $params);
} }
/** /**
...@@ -106,12 +106,6 @@ class Widget extends Component implements Initable ...@@ -106,12 +106,6 @@ class Widget extends Component implements Initable
*/ */
public function createView() public function createView()
{ {
$view = new View; return new View($this);
if (($theme = \Yii::$application->getTheme()) !== null) {
$view->basePath[] = $theme->getViewPath() . DIRECTORY_SEPARATOR . str_replace('\\', '_', get_class($this));
}
$class = new \ReflectionClass($this);
$view->basePath[] = dirname($class->getFileName()) . DIRECTORY_SEPARATOR . 'views';
return $view;
} }
} }
\ No newline at end of file
...@@ -47,7 +47,7 @@ ...@@ -47,7 +47,7 @@
* @package system.caching * @package system.caching
* @since 1.0 * @since 1.0
*/ */
abstract class CCache extends CApplicationComponent implements ICache, 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 which means
...@@ -64,8 +64,8 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce ...@@ -64,8 +64,8 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce
* cache keys, otherwise there might be unexpected behavior. * cache keys, otherwise there might be unexpected behavior.
* @since 1.1.11 * @since 1.1.11
**/ **/
public $hashKey=true; public $hashKey = true;
/** /**
* @var boolean whether to automatically serialize/unserialize the cache values. Defaults to true. Setting this property to false makes sure the cache * @var boolean whether to automatically serialize/unserialize the cache values. Defaults to true. Setting this property to false makes sure the cache
* value will not be tampered when calling the methods {@link set()} and {@link add()}. This is useful in case you want to store data which simply * value will not be tampered when calling the methods {@link set()} and {@link add()}. This is useful in case you want to store data which simply
...@@ -76,7 +76,7 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce ...@@ -76,7 +76,7 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce
* configure a dedicated cache component for the sole purpose of storing raw unserialized data, the main cache component should always support serialization. * configure a dedicated cache component for the sole purpose of storing raw unserialized data, the main cache component should always support serialization.
* @since 1.1.11 * @since 1.1.11
**/ **/
public $autoSerialize=true; public $autoSerialize = true;
/** /**
* @var boolean wether to make use of the {@link http://pecl.php.net/package/igbinary igbinary} serializer for cache entry serialization. Defaults to false. * @var boolean wether to make use of the {@link http://pecl.php.net/package/igbinary igbinary} serializer for cache entry serialization. Defaults to false.
...@@ -84,8 +84,8 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce ...@@ -84,8 +84,8 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce
* serializer. Since the two serialization formats are incompatible, caches should be purged before switching this on to prevent errors. * serializer. Since the two serialization formats are incompatible, caches should be purged before switching this on to prevent errors.
* @since 1.1.11 * @since 1.1.11
*/ */
public $useIgbinarySerializer=false; public $useIgbinarySerializer = false;
/** /**
* Initializes the application component. * Initializes the application component.
* This method overrides the parent implementation by setting default cache key prefix. * This method overrides the parent implementation by setting default cache key prefix.
...@@ -93,9 +93,10 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce ...@@ -93,9 +93,10 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce
public function init() public function init()
{ {
parent::init(); parent::init();
if($this->keyPrefix===null) if ($this->keyPrefix === null) {
$this->keyPrefix=Yii::app()->getId(); $this->keyPrefix = Yii::app()->getId();
$this->useIgbinarySerializer=$this->useIgbinarySerializer&&extension_loaded('igbinary'); }
$this->useIgbinarySerializer = $this->useIgbinarySerializer && extension_loaded('igbinary');
} }
/** /**
...@@ -104,7 +105,7 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce ...@@ -104,7 +105,7 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce
*/ */
protected function generateUniqueKey($key) protected function generateUniqueKey($key)
{ {
return $this->hashKey ? md5($this->keyPrefix.$key) : $this->keyPrefix.$key; return $this->hashKey ? md5($this->keyPrefix . $key) : $this->keyPrefix . $key;
} }
/** /**
...@@ -114,12 +115,10 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce ...@@ -114,12 +115,10 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce
*/ */
public function get($id) public function get($id)
{ {
if(($value=$this->getValue($this->generateUniqueKey($id)))!==false) if (($value = $this->getValue($this->generateUniqueKey($id))) !== false) {
{ $data = $this->autoSerialize ? $this->unserializeValue($value) : $value;
$data=$this->autoSerialize ? $this->unserializeValue($value) : $value; if (!$this->autoSerialize || (is_array($data) && (!($data[1] instanceof ICacheDependency) || !$data[1]->getHasChanged()))) {
if(!$this->autoSerialize || (is_array($data) && (!($data[1] instanceof ICacheDependency) || !$data[1]->getHasChanged()))) Yii::trace('Serving "' . $id . '" from cache', 'system.caching.' . get_class($this));
{
Yii::trace('Serving "'.$id.'" from cache','system.caching.'.get_class($this));
return $this->autoSerialize ? $data[0] : $data; return $this->autoSerialize ? $data[0] : $data;
} }
} }
...@@ -138,23 +137,21 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce ...@@ -138,23 +137,21 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce
*/ */
public function mget($ids) public function mget($ids)
{ {
$uniqueIDs=array(); $uniqueIDs = array();
$results=array(); $results = array();
foreach($ids as $id) foreach ($ids as $id) {
{ $uniqueIDs[$id] = $this->generateUniqueKey($id);
$uniqueIDs[$id]=$this->generateUniqueKey($id); $results[$id] = false;
$results[$id]=false;
} }
$values=$this->getValues($uniqueIDs); $values = $this->getValues($uniqueIDs);
foreach($uniqueIDs as $id=>$uniqueID) foreach ($uniqueIDs as $id => $uniqueID) {
{ if (!isset($values[$uniqueID])) {
if(!isset($values[$uniqueID]))
continue; continue;
$data=$this->autoSerialize ? $this->unserializeValue($values[$uniqueID]) : $values[$uniqueID]; }
if(!$this->autoSerialize || (is_array($data) && (!($data[1] instanceof ICacheDependency) || !$data[1]->getHasChanged()))) $data = $this->autoSerialize ? $this->unserializeValue($values[$uniqueID]) : $values[$uniqueID];
{ if (!$this->autoSerialize || (is_array($data) && (!($data[1] instanceof ICacheDependency) || !$data[1]->getHasChanged()))) {
Yii::trace('Serving "'.$id.'" from cache','system.caching.'.get_class($this)); Yii::trace('Serving "' . $id . '" from cache', 'system.caching.' . get_class($this));
$results[$id]=$this->autoSerialize ? $data[0] : $data; $results[$id] = $this->autoSerialize ? $data[0] : $data;
} }
} }
return $results; return $results;
...@@ -171,13 +168,14 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce ...@@ -171,13 +168,14 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce
* @param ICacheDependency $dependency dependency of the cached item. If the dependency changes, the item is labeled invalid. * @param ICacheDependency $dependency dependency of the cached item. If the dependency changes, the item is labeled invalid.
* @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
*/ */
public function set($id,$value,$expire=0,$dependency=null) public function set($id, $value, $expire = 0, $dependency = null)
{ {
Yii::trace('Saving "'.$id.'" to cache','system.caching.'.get_class($this)); Yii::trace('Saving "' . $id . '" to cache', 'system.caching.' . get_class($this));
if($dependency!==null && $this->autoSerialize) if ($dependency !== null && $this->autoSerialize) {
$dependency->evaluateDependency(); $dependency->evaluateDependency();
$data=$this->autoSerialize ? $this->serializeValue(array($value,$dependency)) : $value; }
return $this->setValue($this->generateUniqueKey($id),$data,$expire); $data = $this->autoSerialize ? $this->serializeValue(array($value, $dependency)) : $value;
return $this->setValue($this->generateUniqueKey($id), $data, $expire);
} }
/** /**
...@@ -189,13 +187,14 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce ...@@ -189,13 +187,14 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce
* @param ICacheDependency $dependency dependency of the cached item. If the dependency changes, the item is labeled invalid. * @param ICacheDependency $dependency dependency of the cached item. If the dependency changes, the item is labeled invalid.
* @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
*/ */
public function add($id,$value,$expire=0,$dependency=null) public function add($id, $value, $expire = 0, $dependency = null)
{ {
Yii::trace('Adding "'.$id.'" to cache','system.caching.'.get_class($this)); Yii::trace('Adding "' . $id . '" to cache', 'system.caching.' . get_class($this));
if($dependency!==null && $this->autoSerialize) if ($dependency !== null && $this->autoSerialize) {
$dependency->evaluateDependency(); $dependency->evaluateDependency();
$data=$this->autoSerialize ? $this->serializeValue(array($value,$dependency)) : $value; }
return $this->addValue($this->generateUniqueKey($id),$data,$expire); $data = $this->autoSerialize ? $this->serializeValue(array($value, $dependency)) : $value;
return $this->addValue($this->generateUniqueKey($id), $data, $expire);
} }
/** /**
...@@ -205,7 +204,7 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce ...@@ -205,7 +204,7 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce
*/ */
public function delete($id) public function delete($id)
{ {
Yii::trace('Deleting "'.$id.'" from cache','system.caching.'.get_class($this)); Yii::trace('Deleting "' . $id . '" from cache', 'system.caching.' . get_class($this));
return $this->deleteValue($this->generateUniqueKey($id)); return $this->deleteValue($this->generateUniqueKey($id));
} }
...@@ -216,7 +215,7 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce ...@@ -216,7 +215,7 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce
*/ */
public function flush() public function flush()
{ {
Yii::trace('Flushing cache','system.caching.'.get_class($this)); Yii::trace('Flushing cache', 'system.caching.' . get_class($this));
return $this->flushValues(); return $this->flushValues();
} }
...@@ -232,8 +231,8 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce ...@@ -232,8 +231,8 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce
*/ */
protected function getValue($key) protected function getValue($key)
{ {
throw new CException(Yii::t('yii','{className} does not support get() functionality.', throw new CException(Yii::t('yii', '{className} does not support get() functionality.',
array('{className}'=>get_class($this)))); array('{className}' => get_class($this))));
} }
/** /**
...@@ -247,9 +246,10 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce ...@@ -247,9 +246,10 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce
*/ */
protected function getValues($keys) protected function getValues($keys)
{ {
$results=array(); $results = array();
foreach($keys as $key) foreach ($keys as $key) {
$results[$key]=$this->getValue($key); $results[$key] = $this->getValue($key);
}
return $results; return $results;
} }
...@@ -266,10 +266,10 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce ...@@ -266,10 +266,10 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce
* @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
* @throws CException if this method is not overridden by child classes * @throws CException if this method is not overridden by child classes
*/ */
protected function setValue($key,$value,$expire) protected function setValue($key, $value, $expire)
{ {
throw new CException(Yii::t('yii','{className} does not support set() functionality.', throw new CException(Yii::t('yii', '{className} does not support set() functionality.',
array('{className}'=>get_class($this)))); array('{className}' => get_class($this))));
} }
/** /**
...@@ -285,10 +285,10 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce ...@@ -285,10 +285,10 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce
* @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
* @throws CException if this method is not overridden by child classes * @throws CException if this method is not overridden by child classes
*/ */
protected function addValue($key,$value,$expire) protected function addValue($key, $value, $expire)
{ {
throw new CException(Yii::t('yii','{className} does not support add() functionality.', throw new CException(Yii::t('yii', '{className} does not support add() functionality.',
array('{className}'=>get_class($this)))); array('{className}' => get_class($this))));
} }
/** /**
...@@ -300,8 +300,8 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce ...@@ -300,8 +300,8 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce
*/ */
protected function deleteValue($key) protected function deleteValue($key)
{ {
throw new CException(Yii::t('yii','{className} does not support delete() functionality.', throw new CException(Yii::t('yii', '{className} does not support delete() functionality.',
array('{className}'=>get_class($this)))); array('{className}' => get_class($this))));
} }
/** /**
...@@ -313,8 +313,8 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce ...@@ -313,8 +313,8 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce
*/ */
protected function flushValues() protected function flushValues()
{ {
throw new CException(Yii::t('yii','{className} does not support flushValues() functionality.', throw new CException(Yii::t('yii', '{className} does not support flushValues() functionality.',
array('{className}'=>get_class($this)))); array('{className}' => get_class($this))));
} }
/** /**
...@@ -329,11 +329,12 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce ...@@ -329,11 +329,12 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce
**/ **/
protected function serializeValue($value) protected function serializeValue($value)
{ {
if($this->useIgbinarySerializer) if ($this->useIgbinarySerializer) {
return igbinary_serialize($value); return igbinary_serialize($value);
}
return serialize($value); return serialize($value);
} }
/** /**
* Unserializes the value after it was retrieved from the actual cache backend. * Unserializes the value after it was retrieved from the actual cache backend.
* This method will be called if {@link autoSerialize} is set to true. Child classes may override this method to change * This method will be called if {@link autoSerialize} is set to true. Child classes may override this method to change
...@@ -346,8 +347,9 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce ...@@ -346,8 +347,9 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce
**/ **/
protected function unserializeValue($value) protected function unserializeValue($value)
{ {
if($this->useIgbinarySerializer) if ($this->useIgbinarySerializer) {
return igbinary_unserialize($value); return igbinary_unserialize($value);
}
return unserialize($value); return unserialize($value);
} }
...@@ -359,7 +361,7 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce ...@@ -359,7 +361,7 @@ abstract class CCache extends CApplicationComponent implements ICache, ArrayAcce
*/ */
public function offsetExists($id) public function offsetExists($id)
{ {
return $this->get($id)!==false; return $this->get($id) !== false;
} }
/** /**
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment