COutputCache
包 | system.web.widgets |
---|---|
继承 | class COutputCache » CFilterWidget » CWidget » CBaseController » CComponent |
实现 | IFilter |
可用自 | 1.0 |
源码 | framework/web/widgets/COutputCache.php |
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 example, 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 four 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.
- varyByLanguage: this specifies whether the cached content should by varied with the user's language. Available since 1.1.14.
公共属性
属性 | 类型 | 描述 | 被定义在 |
---|---|---|---|
actionPrefix | string | the prefix to the IDs of the actions. | CWidget |
cacheID | string | the ID of the cache application component. | COutputCache |
controller | CController | Returns 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 | Returns the ID of the widget or generates a new one if requested. | 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 | Returns the 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 |
skin | mixed | the name of the skin to be used by this widget. | CWidget |
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 |
varyByLanguage | boolean | whether the content being cached should be differentiated according to user's language. | 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 |
受保护的属性
属性 | 类型 | 描述 | 被定义在 |
---|---|---|---|
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 |
公共方法
方法 | 描述 | 被定义在 |
---|---|---|
__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 |
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent |
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 the ID of the widget or generates a new one if requested. | 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 the owner/creator of this widget. | 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 the ID of the widget. | CWidget |
widget() | Creates a widget and executes it. | CBaseController |
受保护的方法
方法 | 描述 | 被定义在 |
---|---|---|
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 |
属性详情
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.
the cache used for caching the content.
the ID of the cache application component. Defaults to 'cache' (the primary cache application component.)
Calculates the cache key. The key is calculated based on getBaseCacheKey and other factors, including varyByRoute, varyByParam, varyBySession and varyByLanguage.
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.
number of seconds that the data can remain in cache. Defaults to 60 seconds.
If it is 0, existing cached content would be removed from the cache.
If it is a negative value, the cache will be disabled (any existing cached content will
remain in the cache.)
Note, if cache dependency changes or cache space is limited,
the data may be purged out of cache earlier.
whether the content can be found from cache
list of request types (e.g. GET, POST) for which the cache should be enabled only. Defaults to null, meaning all request types.
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. 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 signature should be as follows:
function foo($cache) { ... }where $cache refers to the output cache component.
The PHP expression will be evaluated using evaluateExpression.
A PHP expression can be any PHP code that has a value. To learn more about what an expression is, please refer to the php manual.
whether the content being cached should be differentiated according to user's language. A language is retrieved via Yii::app()->language. Defaults to false.
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.
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.
whether the content being cached should be differentiated according to user sessions. Defaults to false.
方法详情
protected boolean checkContentCache()
| ||
{return} | boolean | whether the content is found in cache. |
protected function checkContentCache()
{
if((empty($this->requestTypes) || in_array(Yii::app()->getRequest()->getRequestType(),$this->requestTypes))
&& ($this->_cache=$this->getCache())!==null)
{
if($this->duration>0 && ($data=$this->_cache->get($this->getCacheKey()))!==false)
{
$this->_content=$data[0];
$this->_actions=$data[1];
return true;
}
if($this->duration==0)
$this->_cache->delete($this->getCacheKey());
if($this->duration<=0)
$this->_cache=null;
}
return false;
}
Looks for content in cache.
public boolean filter(CFilterChain $filterChain)
| ||
$filterChain | CFilterChain | list of filters being applied to an action |
{return} | boolean | whether the filtering process should stop after this filter. Defaults to false. |
public function filter($filterChain)
{
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.
protected string getBaseCacheKey()
| ||
{return} | string | basic cache key without variations |
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.
protected ICache getCache()
| ||
{return} | ICache | the cache used for caching the content. |
protected function getCache()
{
return Yii::app()->getComponent($this->cacheID);
}
protected string getCacheKey()
| ||
{return} | string | cache key |
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.='.';
if($this->varyByLanguage)
$key.=Yii::app()->language;
$key.='.';
return $this->_key=$key;
}
}
Calculates the cache key. The key is calculated based on getBaseCacheKey and other factors, including varyByRoute, varyByParam, varyBySession and varyByLanguage.
public boolean getIsContentCached()
| ||
{return} | boolean | whether the content can be found from cache |
public function getIsContentCached()
{
if($this->_contentCached!==null)
return $this->_contentCached;
else
return $this->_contentCached=$this->checkContentCache();
}
public void init()
|
public function init()
{
if($this->getIsContentCached())
$this->replayActions();
elseif($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.
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 |
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.
protected void replayActions()
|
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;
elseif($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]);
elseif($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.
public void run()
|
public function run()
{
if($this->getIsContentCached())
{
if($this->getController()->isCachingStackEmpty())
echo $this->getController()->processDynamicOutput($this->_content);
else
echo $this->_content;
}
elseif($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->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.