0 follower

COutputCache

Package system.web.widgets
Inheritance class COutputCache » CFilterWidget » CWidget » CBaseController » CComponent
Implements IFilter
Since 1.0
Version $Id$
Source Code framework/web/widgets/COutputCache.php
COutputCache enables caching the output generated by an action or a view fragment.

If the output to be displayed is found valid in cache, the cached version will be displayed instead, which saves the time for generating the original output.

Since COutputCache extends from CFilterWidget, it can be used as either a filter (for action caching) or a widget (for fragment caching). For the latter, the shortcuts CBaseController::beginCache() and CBaseController::endCache() are often used instead, like the following in a view file:
if($this->beginCache('cacheName',array('property1'=>'value1',...))
{
    // ... display the content to be cached here
   $this->endCache();
}


COutputCache must work with a cache application component specified via cacheID. If the cache application component is not available, COutputCache will be disabled.

The validity of the cached content is determined based on two factors: the duration and the cache dependency. The former specifies the number of seconds that the data can remain valid in cache (defaults to 60s), while the latter specifies conditions that the cached data depends on. If a dependency changes, (e.g. relevant data in DB are updated), the cached data will be invalidated. For more details about cache dependency, see CCacheDependency.

Sometimes, it is necessary to turn off output caching only for certain request types. For exapmle, we only want to cache a form when it is initially requested; any subsequent display of the form should not be cached because it contains user input. We can set requestTypes to be array('GET') to accomplish this task.

The content fetched from cache may be variated with respect to some parameters. COutputCache supports two kinds of variations:
  • varyByRoute: this specifies whether the cached content should be varied with the requested route (controller and action)
  • varyByParam: this specifies a list of GET parameter names and uses the corresponding values to determine the version of the cached content.
  • varyBySession: this specifies whether the cached content should be varied with the user session.
  • varyByExpression: this specifies whether the cached content should be varied with the result of the specified PHP expression.
For more advanced variation, override getBaseCacheKey() method.

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
actionPrefix string the prefix to the IDs of the actions. CWidget
cacheID string the ID of the cache application component. COutputCache
controller CController the controller that this widget belongs to. CWidget
dependency mixed the dependency that the cached content depends on. COutputCache
duration integer number of seconds that the data can remain in cache. COutputCache
id string id of the widget. CWidget
isContentCached boolean whether the content can be found from cache COutputCache
isFilter boolean whether this widget is used as a filter. CFilterWidget
owner CBaseController owner/creator of this widget. CWidget
requestTypes array list of request types (e.g. GET, POST) for which the cache should be enabled only. COutputCache
stopAction boolean whether to stop the action execution when this widget is used as a filter. CFilterWidget
varyByExpression string a PHP expression whose result is used in the cache key calculation. COutputCache
varyByParam array list of GET parameters that should participate in cache key calculation. COutputCache
varyByRoute boolean whether the content being cached should be differentiated according to route. COutputCache
varyBySession boolean whether the content being cached should be differentiated according to user sessions. COutputCache
viewPath string Returns the directory containing the view files for this widget. CWidget

Protected Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
baseCacheKey string Caclulates the base cache key. COutputCache
cache ICache the cache used for caching the content. COutputCache
cacheKey string Calculates the cache key. COutputCache

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. CComponent
__construct() Constructor. CFilterWidget
__get() Returns a property value, an event handler list or a behavior based on its name. CComponent
__isset() Checks if a property value is null. CComponent
__set() Sets value of a component property. CComponent
__unset() Sets a component property to be null. CComponent
actions() Returns a list of actions that are used by this widget. CWidget
asa() Returns the named behavior object. CComponent
attachBehavior() Attaches a behavior to this component. CComponent
attachBehaviors() Attaches a list of behaviors to the component. CComponent
attachEventHandler() Attaches an event handler to an event. CComponent
beginCache() Begins fragment caching. CBaseController
beginClip() Begins recording a clip. CBaseController
beginContent() Begins the rendering of content that is to be decorated by the specified view. CBaseController
beginWidget() Creates a widget and executes it. CBaseController
canGetProperty() Determines whether a property can be read. CComponent
canSetProperty() Determines whether a property can be set. CComponent
createWidget() Creates a widget and initializes it. CBaseController
detachBehavior() Detaches a behavior from the component. CComponent
detachBehaviors() Detaches all behaviors from the component. CComponent
detachEventHandler() Detaches an existing event handler. CComponent
disableBehavior() Disables an attached behavior. CComponent
disableBehaviors() Disables all behaviors attached to this component. CComponent
enableBehavior() Enables an attached behavior. CComponent
enableBehaviors() Enables all behaviors attached to this component. CComponent
endCache() Ends fragment caching. CBaseController
endClip() Ends recording a clip. CBaseController
endContent() Ends the rendering of content. CBaseController
endWidget() Ends the execution of the named widget. CBaseController
filter() Performs filtering before the action is executed. COutputCache
getController() Returns the controller that this widget belongs to. CWidget
getEventHandlers() Returns the list of attached event handlers for an event. CComponent
getId() Returns id of the widget. CWidget
getIsContentCached() Checks whether the content can be found from cache COutputCache
getIsFilter() Checks whether this widget is used as a filter. CFilterWidget
getOwner() Returns owner/creator of this widget. It could be either a widget or a controller. CWidget
getViewFile() Looks for the view script file according to the view name. CWidget
getViewPath() Returns the directory containing the view files for this widget. CWidget
hasEvent() Determines whether an event is defined. CComponent
hasEventHandler() Checks whether the named event has attached handlers. CComponent
hasProperty() Determines whether a property is defined. CComponent
init() Marks the start of content to be cached. COutputCache
raiseEvent() Raises an event. CComponent
recordAction() Records a method call when this output cache is in effect. COutputCache
render() Renders a view. CWidget
renderFile() Renders a view file. CBaseController
renderInternal() Renders a view file. CBaseController
run() Marks the end of content to be cached. COutputCache
setId() Sets id of the widget. CWidget
widget() Creates a widget and executes it. CBaseController

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
checkContentCache() Looks for content in cache. COutputCache
getBaseCacheKey() Caclulates the base cache key. COutputCache
getCache() Returns the cache used for caching the content. COutputCache
getCacheKey() Calculates the cache key. COutputCache
replayActions() Replays the recorded method calls. COutputCache

Property Details

baseCacheKey property read-only
protected string getBaseCacheKey()

Caclulates the base cache key. The calculated key will be further variated in getCacheKey. Derived classes may override this method if more variations are needed.

cache property read-only
protected ICache getCache()

the cache used for caching the content.

cacheID property
public string $cacheID;

the ID of the cache application component. Defaults to 'cache' (the primary cache application component.)

cacheKey property read-only
protected string getCacheKey()

Calculates the cache key. The key is calculated based on getBaseCacheKey and other factors, including varyByRoute, varyByParam and varyBySession.

dependency property
public mixed $dependency;

the dependency that the cached content depends on. This can be either an object implementing ICacheDependency interface or an array specifying the configuration of the dependency object. For example,

array(
    'class'=>'CDbCacheDependency',
    'sql'=>'SELECT MAX(lastModified) FROM Post',
)
would make the output cache depends on the last modified time of all posts. If any post has its modification time changed, the cached content would be invalidated.

duration property
public integer $duration;

number of seconds that the data can remain in cache. Defaults to 60 seconds. If 0 or negative, it means the cache is disabled. Note, if cache dependency changes or cache space is limited, the data may be purged out of cache earlier.

isContentCached property read-only
public boolean getIsContentCached()

whether the content can be found from cache

requestTypes property
public array $requestTypes;

list of request types (e.g. GET, POST) for which the cache should be enabled only. Defaults to null, meaning all request types.

varyByExpression property (available since v1.0.4)
public string $varyByExpression;

a PHP expression whose result is used in the cache key calculation. By setting this property, the output cache will use different cached data for each different expression result. Starting from version 1.0.11, the expression can also be a valid PHP callback, including class method name (array(ClassName/Object, MethodName)), or anonymous function (PHP 5.3.0+). The function/method will be passed a single parameter which is the output cache object itself.

varyByParam property
public array $varyByParam;

list of GET parameters that should participate in cache key calculation. By setting this property, the output cache will use different cached data for each different set of GET parameter values.

varyByRoute property
public boolean $varyByRoute;

whether the content being cached should be differentiated according to route. A route consists of the requested controller ID and action ID. Defaults to true.

varyBySession property
public boolean $varyBySession;

whether the content being cached should be differentiated according to user sessions. Defaults to false.

Method Details

checkContentCache() method
protected boolean checkContentCache()
{return} boolean whether the content is found in cache.
Source Code: framework/web/widgets/COutputCache.php#212 (show)
protected function checkContentCache()
{
    if((empty(
$this->requestTypes) || in_array(Yii::app()->getRequest()->getRequestType(),$this->requestTypes))
        && 
$this->duration>&& ($this->_cache=$this->getCache())!==null)
    {
        if((
$data=$this->_cache->get($this->getCacheKey()))!==false)
        {
            
$this->_content=$data[0];
            
$this->_actions=$data[1];
            return 
true;
        }
    }
    return 
false;
}

Looks for content in cache.

filter() method
public boolean filter($filterChain)
$filterChain
{return} boolean whether the filtering process should stop after this filter. Defaults to false.
Source Code: framework/web/widgets/COutputCache.php#140 (show)
public function filter($filterChain)
{
    
$this->init();
    if(!
$this->getIsContentCached())
        
$filterChain->run();
    
$this->run();
}

Performs filtering before the action is executed. This method is meant to be overridden by child classes if begin-filtering is needed.

getBaseCacheKey() method
protected string getBaseCacheKey()
{return} string basic cache key without variations
Source Code: framework/web/widgets/COutputCache.php#241 (show)
protected function getBaseCacheKey()
{
    return 
self::CACHE_KEY_PREFIX.$this->getId().'.';
}

Caclulates the base cache key. The calculated key will be further variated in getCacheKey. Derived classes may override this method if more variations are needed.

getCache() method
protected ICache getCache()
{return} ICache the cache used for caching the content.
Source Code: framework/web/widgets/COutputCache.php#230 (show)
protected function getCache()
{
    return 
Yii::app()->getComponent($this->cacheID);
}

getCacheKey() method
protected string getCacheKey()
{return} string cache key
Source Code: framework/web/widgets/COutputCache.php#252 (show)
protected function getCacheKey()
{
    if(
$this->_key!==null)
        return 
$this->_key;
    else
    {
        
$key=$this->getBaseCacheKey().'.';
        if(
$this->varyByRoute)
        {
            
$controller=$this->getController();
            
$key.=$controller->getUniqueId().'/';
            if((
$action=$controller->getAction())!==null)
                
$key.=$action->getId();
        }
        
$key.='.';

        if(
$this->varyBySession)
            
$key.=Yii::app()->getSession()->getSessionID();
        
$key.='.';

        if(
is_array($this->varyByParam) && isset($this->varyByParam[0]))
        {
            
$params=array();
            foreach(
$this->varyByParam as $name)
            {
                if(isset(
$_GET[$name]))
                    
$params[$name]=$_GET[$name];
                else
                    
$params[$name]='';
            }
            
$key.=serialize($params);
        }
        
$key.='.';

        if(
$this->varyByExpression!==null)
            
$key.=$this->evaluateExpression($this->varyByExpression);
        
$key.='.';

        return 
$this->_key=$key;
    }
}

Calculates the cache key. The key is calculated based on getBaseCacheKey and other factors, including varyByRoute, varyByParam and varyBySession.

getIsContentCached() method
public boolean getIsContentCached()
{return} boolean whether the content can be found from cache
Source Code: framework/web/widgets/COutputCache.php#200 (show)
public function getIsContentCached()
{
    if(
$this->_contentCached!==null)
        return 
$this->_contentCached;
    else
        return 
$this->_contentCached=$this->checkContentCache();
}

init() method
public void init()
Source Code: framework/web/widgets/COutputCache.php#154 (show)
public function init()
{
    if(
$this->getIsContentCached())
        
$this->replayActions();
    else if(
$this->_cache!==null)
    {
        
$this->getController()->getCachingStack()->push($this);
        
ob_start();
        
ob_implicit_flush(false);
    }
}

Marks the start of content to be cached. Content displayed after this method call and before endCache() will be captured and saved in cache. This method does nothing if valid content is already found in cache.

recordAction() method
public void recordAction(string $context, string $method, array $params)
$context string a property name of the controller. The property should refer to an object whose method is being recorded. If empty it means the controller itself.
$method string the method name
$params array parameters passed to the method
Source Code: framework/web/widgets/COutputCache.php#311 (show)
public function recordAction($context,$method,$params)
{
    
$this->_actions[]=array($context,$method,$params);
}

Records a method call when this output cache is in effect. When the content is served from the output cache, the recorded method will be re-invoked.

replayActions() method
protected void replayActions()
Source Code: framework/web/widgets/COutputCache.php#319 (show)
protected function replayActions()
{
    if(empty(
$this->_actions))
        return;
    
$controller=$this->getController();
    
$cs=Yii::app()->getClientScript();
    foreach(
$this->_actions as $action)
    {
        if(
$action[0]==='clientScript')
            
$object=$cs;
        else if(
$action[0]==='')
            
$object=$controller;
        else
            
$object=$controller->{$action[0]};
        if(
method_exists($object,$action[1]))
            
call_user_func_array(array($object,$action[1]),$action[2]);
        else if(
$action[0]==='' && function_exists($action[1]))
            
call_user_func_array($action[1],$action[2]);
        else
            throw new 
CException(Yii::t('yii','Unable to replay the action "{object}.{method}". The method does not exist.',
                array(
'object'=>$action[0],
                    
'method'=>$action[1])));
    }
}

Replays the recorded method calls.

run() method
public void run()
Source Code: framework/web/widgets/COutputCache.php#172 (show)
public function run()
{
    if(
$this->getIsContentCached())
    {
        if(
$this->getController()->isCachingStackEmpty())
            echo 
$this->getController()->processDynamicOutput($this->_content);
        else
            echo 
$this->_content;
    }
    else if(
$this->_cache!==null)
    {
        
$this->_content=ob_get_clean();
        
$this->getController()->getCachingStack()->pop();
        
$data=array($this->_content,$this->_actions);
        if(
is_array($this->dependency))
            
$this->dependency=Yii::createComponent($this->dependency);
        
$this->_cache->set($this->getCacheKey(),$data,$this->duration>$this->duration 0,$this->dependency);

        if(
$this->getController()->isCachingStackEmpty())
            echo 
$this->getController()->processDynamicOutput($this->_content);
        else
            echo 
$this->_content;
    }
}

Marks the end of content to be cached. Content displayed before this method call and after init() will be captured and saved in cache. This method does nothing if valid content is already found in cache.