Detailed description of Cache Usage in the YII Framework tutorial, yiiframework

Source: Internet
Author: User
Tags apc

Detailed description of Cache Usage in the YII Framework tutorial, yiiframework

This example describes the YII Framework cache usage. We will share this with you for your reference. The details are as follows:

The reason for cache generation is well known. Therefore, YII, as an efficient and easy-to-use framework, cannot help but support caching. Therefore, YII provides interfaces for various popular caches. You can use different caches as needed.

1. Introduction to cache in YII

The cache in YII is defined by components.

/Yii_dev/yii/framework/caching # tree
.
├ ── CApcCache. php
├ ── CCache. php
├ ── CDbCache. php
├ ── CDummyCache. php
├ ── CEAcceleratorCache. php
── CFileCache. php
── CMemCache. php
── CWinCache. php
├ ── CXCache. php
├ ── CZendDataCache. php
── Dependencies
── CCacheDependency. php
── CChainedCacheDependency. php
├ ── CDbCacheDependency. php
── CDirectoryCacheDependency. php
── CExpressionDependency. php
── CFileCacheDependency. php
── CGlobalStateCacheDependency. php

1 directory, 17 files

The original official text is explained as follows:

Yii provides different cache components to store cached data in different media. For example, the CMemCache component encapsulates the memcache extension of PHP and uses the memory as the cache storage medium. The CApcCache component encapsulates php apc extensions, while the CDbCache component saves cached data to the database. The following is a list of available cache components:

CMemCache: Use PHP memcache extension.

CApcCache: php apc extension.

CXCache: Use PHP XCache extension. Note that this is supported from version 1.0.1.

CEAcceleratorCache: Use PHP EAccelerator extension.

CDbCache: uses a data table to store cached data. By default, it creates and uses a SQLite3 database under the runtime directory. You can also specify a database for it by setting its connectionID attribute.

CZendDataCache: Use Zend Data Cache as the backend Cache medium. Note that this is supported from version 1.0.4.

CFileCache: Uses files to store cached data. This is especially suitable for storing large volumes of data (such as pages ). Note that this is supported from version 1.0.6.

CDummyCache: currently, dummy cache does not support caching. The purpose of this component is to simplify the code that needs to check the cache availability. For example, you can use this cache component when the development stage or the server does not yet support the actual cache function. After the actual cache support is enabled, we can switch to the corresponding cache component. In both cases, we can use the same code Yii: app ()-> cache-> get ($ key) to retrieve data fragments without worrying about Yii :: app ()-> cache may be null. This component is supported from version 1.0.5.

Tip: because all these cache components inherit from the same base class CCache, you can switch to another caching method without changing the code that uses the cache.

Cache can be used at different levels. At the lowest level, we use the cache to store a single data segment, such as a variable, which we call data caching ). In the next level, we store a page segment generated by a part of the View Script in the cache. At the highest level, we store the entire page in the cache and retrieve it as needed.

In the following sections, we will explain in detail how to use caching at these levels.

Note: As defined, cache is an unstable storage medium. Even if no timeout occurs, it does not ensure that the cached data exists. Therefore, do not use the cache as persistent storage. (For example, do not use the cache to store Session data ).

2. cache configuration and call Method

The cache in yii is mainly implemented through components. You can configure the cache by specifying the cache class.

It is usually a class that specifies the cache component.

For example, apc

'cache'=>array(  'class'=>'system.caching.CApcCache'),

The memcache configuration method may be

* array(*   'components'=>array(*     'cache'=>array(*       'class'=>'CMemCache',*       'servers'=>array(*         array(*           'host'=>'server1',*           'port'=>11211,*           'weight'=>60,*         ),*         array(*           'host'=>'server2',*           'port'=>11211,*           'weight'=>40,*         ),*       ),*     ),*   ),* )

Usage:

Yii encapsulates methods for different cache operations, mainly in CCache. CCache is the base class of all Cache classes. Therefore, after the cache is configured, the call method is simple:

<?php/** * CCache is the base class for cache classes with different cache storage implementation. * * A data item can be stored in cache by calling {@link set} and be retrieved back * later by {@link get}. In both operations, a key identifying the data item is required. * An expiration time and/or a dependency can also be specified when calling {@link set}. * If the data item expires or the dependency changes, calling {@link get} will not * return back the data item. * * Note, by definition, cache does not ensure the existence of a value * even if it does not expire. Cache is not meant to be a persistent storage. * * CCache implements the interface {@link ICache} with the following methods: * <ul> * <li>{@link get} : retrieve the value with a key (if any) from cache</li> * <li>{@link set} : store the value with a key into cache</li> * <li>{@link add} : store the value only if cache does not have this key</li> * <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: * <ul> * <li>{@link getValue}</li> * <li>{@link setValue}</li> * <li>{@link addValue}</li> * <li>{@link deleteValue}</li> * <li>{@link flush} (optional)</li> * </ul> * * CCache also implements ArrayAccess so that it can be used like an array. * * @author Qiang Xue <qiang.xue@gmail.com> * @version $Id: CCache.php 3001 2011-02-24 16:42:44Z alexander.makarow $ * @package system.caching * @since 1.0 */abstract class CCache extends CApplicationComponent implements ICache, ArrayAccess{

According to the CCache class description, we can see that the common cache operation methods include get, set, add, delete, and flush.

/** * Retrieves a value from cache with a specified key. * @param string $id a key identifying the cached value * @return mixed the value stored in cache, false if the value is not in the cache, expired or the dependency has changed. */public function get($id){  if(($value=$this->getValue($this->generateUniqueKey($id)))!==false)  {    $data=unserialize($value);    if(!is_array($data))      return false;    if(!($data[1] instanceof ICacheDependency) || !$data[1]->getHasChanged())    {      Yii::trace('Serving "'.$id.'" from cache','system.caching.'.get_class($this));      return $data[0];    }  }  return false;}/** * Retrieves multiple values from cache with the specified keys. * Some caches (such as memcache, apc) allow retrieving multiple cached values at one time, * which may improve the performance since it reduces the communication cost. * In case a cache doesn't support this feature natively, it will be simulated by this method. * @param array $ids list of keys identifying the cached values * @return array list of cached values corresponding to the specified keys. The array * is returned in terms of (key,value) pairs. * If a value is not cached or expired, the corresponding array value will be false. * @since 1.0.8 */public function mget($ids){  $uniqueIDs=array();  $results=array();  foreach($ids as $id)  {    $uniqueIDs[$id]=$this->generateUniqueKey($id);    $results[$id]=false;  }  $values=$this->getValues($uniqueIDs);  foreach($uniqueIDs as $id=>$uniqueID)  {    if(!isset($values[$uniqueID]))      continue;    $data=unserialize($values[$uniqueID]);    if(is_array($data) && (!($data[1] instanceof ICacheDependency) || !$data[1]->getHasChanged()))    {      Yii::trace('Serving "'.$id.'" from cache','system.caching.'.get_class($this));      $results[$id]=$data[0];    }  }  return $results;}/** * Stores a value identified by a key into cache. * If the cache already contains such a key, the existing value and * expiration time will be replaced with the new ones. * * @param string $id the key identifying 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 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 */public function set($id,$value,$expire=0,$dependency=null){  Yii::trace('Saving "'.$id.'" to cache','system.caching.'.get_class($this));  if($dependency!==null)    $dependency->evaluateDependency();  $data=array($value,$dependency);  return $this->setValue($this->generateUniqueKey($id),serialize($data),$expire);}/** * Stores a value identified by a key into cache if the cache does not contain this key. * Nothing will be done if the cache already contains the key. * @param string $id the key identifying 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 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 */public function add($id,$value,$expire=0,$dependency=null){  Yii::trace('Adding "'.$id.'" to cache','system.caching.'.get_class($this));  if($dependency!==null)    $dependency->evaluateDependency();  $data=array($value,$dependency);  return $this->addValue($this->generateUniqueKey($id),serialize($data),$expire);}/** * Deletes a value with the specified key from cache * @param string $id the key of the value to be deleted * @return boolean if no error happens during deletion */public function delete($id){  Yii::trace('Deleting "'.$id.'" from cache','system.caching.'.get_class($this));  return $this->deleteValue($this->generateUniqueKey($id));}/** * Deletes all values from cache. * Be careful of performing this operation if the cache is shared by multiple applications. * @return boolean whether the flush operation was successful. */public function flush(){  Yii::trace('Flushing cache','system.caching.'.get_class($this));  return $this->flushValues();}

That is:

Yii::app()->cache->xxx

Xxx corresponds to the specific method.

For example:

$id = 'key1';$value = 'cache value';Yii::app()->cache->add($id, $value);var_dump(Yii::app()->cache->get($id));

The following describes the usage of several caching Methods officially provided by yii.

3. Cache Usage: Data Cache

Data Cache

Data cache stores some PHP variables in the cache and then retrieves them from the cache. For this purpose, the basic class CCache of the cache component provides two common methods: set () and get ().

To store a variable $ value in the cache, we select a unique ID and call set () to store it:

Yii::app()->cache->set($id, $value);

Cached data will remain in the cache unless it is cleared due to some cache policies (such as the cache space is full and old data is deleted. To change this behavior, we can provide an expiration parameter while calling set (), so that the cache data will be cleared after the set time period:

// Value $ value can be reserved in the cache for up to 30 seconds. Yii: app ()-> cache-> set ($ id, $ value, 30 );

Later, when we need to access this variable (in the same or different Web requests), we can call get () by ID to retrieve it from the cache. If the returned value is false, it indicates that the value is not available in the cache. We should generate it again.

$ Value = Yii: app ()-> cache-> get ($ id); if ($ value = false) {// because $ value is not found in the cache, generate it again, // and store it in the cache for future use: // Yii: app () -> cache-> set ($ id, $ value );}

When selecting an ID for the variable to be saved to the cache, make sure that this ID is unique to all other variables stored in the cache in the application. This ID does not need to be unique between different applications. The cache component is smart enough to distinguish IDs of different applications.

Some cache storages, such as MemCache and APC, support obtaining multiple cache values in batch mode. This reduces the overhead of obtaining cached data. From version 1.0.8, Yii provides a new method named mget. It can use this function. If the underlying cache memory does not support this function, mget () can simulate it.

To clear a cache value from the cache, call delete (); to clear all the data in the cache, call flush (). Be careful when calling flush () because it will clear the cache in other applications at the same time.

Tip: Because CCache implements ArrayAccess, the cache component can also be used like an array. The following are examples:

$ Cache = Yii: app ()-> cache; $ cache ['var1'] = $ value1; // equivalent to: $ cache-> set ('var1 ', $ value1); $ value2 = $ cache ['var2']; // equivalent to: $ value2 = $ cache-> get ('var2 ');

1. cache dependency

Besides the expiration settings, cached data may also become invalid due to changes in the dependency conditions. For example, if we cache the content of some files and these files change, we should invalidate the cached data and read the latest content from the file rather than from the cache.

We represent a dependency as an instance of CCacheDependency or its subclass. When set () is called, the data to be cached is passed in together with the data to be cached.

// This value will expire 30 seconds later // it may also become faster and become invalid due to changes in the dependent file. Yii: app ()-> cache-> set ($ id, $ value, 30, new CFileCacheDependency ('filename '));

Now, if we get $ value from the cache by calling get (), the dependency will be checked. If it changes, we will get a false value, indicating that the data needs to be regenerated.

The following is a brief description of available cache dependencies:

CFileCacheDependency: if the last modification time of the file changes, the dependency changes.
CDirectoryCacheDependency: If the Directory and the files in its subdirectories change, the dependency changes.
CDbCacheDependency: If the query result of a specified SQL statement changes, the dependency changes.
CGlobalStateCacheDependency: if the specified global status changes, the dependency changes. The global status is a cross-request and cross-session variable in the application. It is defined by CApplication: setGlobalState.
CChainedCacheDependency: if any dependency in the chain changes, the dependency changes.
CExpressionDependency: if the result of the specified PHP expression changes, the dependency changes. This class is available from version 1.0.4.

4. Cache Usage: fragment Cache

Fragment Caching)

Fragment caching refers to caching a webpage clip. For example, if a page displays the annual sales Summary In the table, we can store the table in the cache to reduce the time for each request to be re-generated.

To use the segment cache, call CController: beginCache () and CController: endCache () in the Controller View Script (). The page content included in the start and end of the two methods will be cached. Similar to data caching, we need a number to identify cached fragments.

Other HTML contents... <? Php if ($ this-> beginCache ($ id) {?>... Cached content... <? Php $ this-> endCache () ;}?>... Other HTML content...

In the preceding example, if beginCache () returns false, the cached content is automatically inserted here. Otherwise, the content in the if statement is executed and cached when endCache () is triggered.

1. cache Options)

When beginCache () is called, an array composed of cache options can be provided as the second parameter to customize fragment caching. In fact, for convenience, the beginCache () and endCache () methods are the packaging of [COutputCache] widgets. Therefore, all attributes of COutputCache can be initialized in the cache options.

Validity Period (Duration)

Perhaps the most common option is duration, which specifies how long the content will be effective in the cache. It is similar to the CCache: set () Expiration parameter. The following code caches content segments for at most one hour:

Other HTML contents... <? Php if ($ this-> beginCache ($ id, array ('duration' => 3600) {?>... Cached content... <? Php $ this-> endCache () ;}?>... Other HTML content...

If we do not set the period, the default value is 60, which means that the cache content will be invalid after 60 seconds.

Dependency)

Like data caching, content fragments can also be cached. For example, whether the content of an article is displayed depends on whether it is modified.

To specify a dependency, we have established the dependency option, which can be an object that implements [ICacheDependency] or a configuration array that can be used to generate dependency objects. The following code specifies whether the part content varies depending on the value of the lastModified column:

Other HTML contents... <? Php if ($ this-> beginCache ($ id, array ('dependency '=> array ('class' => 'System. caching. dependencies. CDbCacheDependency ',' SQL '=> 'select MAX (lastModified) FROM Post') {?>... Cached content... <? Php $ this-> endCache () ;}?>... Other HTML content...

Variation)

The cached content varies according to some parameters. For example, each person has different archives. The cached file content varies according to each person's ID. This means that different IDs are used when beginCache () is called.

COutputCache is built in with this feature, so programmers do not need to write a pattern that changes content based on the ID. The following is a summary.

VaryByRoute: set this option to true, and the cached content will change according to the route. Therefore, each controller and action combination will have a separate cache content.
VaryBySession: set this option to true. The cached content changes according to the session ID. Therefore, each user session may see different content provided by the cache.
VaryByParam: Set the name in the array of this option. The cached content changes according to the value of the GET parameter. For example, if a page displays the content of an article based on the GET parameter of id, we can specify varyByParam as array ('id') so that we can cache the content of each article. Without such changes, we can only cache an article.

VaryByExpression: by setting this option to a PHP expression, we can make the cached content to be variated according to the result of this PHP expression. This option has been available since version 1.0.4.
Request Types

Sometimes, we want the fragment cache to only enable some types of requests. For example, for a form displayed on a webpage, we only want to cache the initially requested form (through the GET request ). Any Form subsequently displayed (via POST request) will not be cached because the form may contain user input. To do this, we can specify the requestTypes option:

Other HTML contents... <? Php if ($ this-> beginCache ($ id, array ('requesttypes '=> array ('get') {?>... Cached content... <? Php $ this-> endCache () ;}?>... Other HTML content...

2. Nested cache (Nested Caching)

Fragment cache can be nested. That is to say, a cache segment is attached to a larger segment cache. For example, the comments are cached in the internal segment, and they are cached in the article content together in the external cache.

Other HTML contents... <? Php if ($ this-> beginCache ($ id1) {?>... Externally cached content... <? Php if ($ this-> beginCache ($ id2) {?> Contents cached inside... <? Php $ this-> endCache () ;}?>... Externally cached content... <? Php $ this-> endCache () ;}?>... Other HTML content...

You can set different cache options for nested caching. For example, in the above example, you can set the duration of the internal cache and the external cache. When data is stored in the external cache, the internal cache can still provide valid internal segments. However, vice versa. If the external cache contains valid data, it will always keep the cached copy even if the internal cache in the content has expired.

5. Cache Usage: Page Cache

Page Cache

Page caching refers to caching the content of the entire page. The page cache can occur in different places. For example, by selecting an appropriate page header, the browser on the client may cache the webpage for a limited time. Web applications can also store Web content in the cache. In this section, we focus on the next approach.

Page cache can be seen as a special case of fragment caching. Because the webpage content is often generated through the Application layout, if we simply call beginCache () and endCache () in the layout, it will not work normally. This is because the layout in the CController: render () method is loaded after the page content is generated.

To Cache the entire page, we should skip the action that generates the page content. We can use COutputCache as the action filter to complete this task. The following code demonstrates how to configure a cache filter:

public function filters(){  return array(    array(      'COutputCache',      'duration'=>100,      'varyByParam'=>array('id'),    ),  );}

The above filter configuration will apply the filter to all actions in the controller. We may restrict it in one or several actions by using the plug-in operator. For more details, see the filter.

Tip: We can use COutputCache as a filter because it inherits from CFilterWidget, which means it is a tool (widget) and a filter. In fact, the widget works in a similar way as a filter: the tool widget (filter) is executed before the content in the action is executed and ends after execution.

6. Use of cache: Dynamic Content

Dynamic Content)

When fragment caching or page caching is used, we often encounter such a situation where the entire part of the output is static except for some places. For example, the Help page may display static help information, while the User Name displays the current user.

To solve this problem, we can match the cached content based on the user name, but this will be a huge waste of our valuable space, because most of the content in the cache except the user name is the same. We can also cut the webpage into several fragments and cache them separately, but this situation will make the page and code very complicated. A better way is to use the dynamic content function provided by [CController.

Dynamic Content means that fragment output is not cached even in the content included in the fragment cache. Even if the included content is retrieved from the cache, in order to make the Dynamic Content Dynamic at all times, it must be regenerated each time. For this reason, dynamic content is required to be generated using some methods or functions.

Call CController: renderDynamic () to insert dynamic content where you want it.

Other HTML contents... <? Php if ($ this-> beginCache ($ id) {?>... Cached fragment content... <? Php $ this-> renderDynamic ($ callback);?>... Cached fragment content... <? Php $ this-> endCache () ;}?>... Other HTML content...

Above, $ callback refers to a valid PHP callback. It can be a string name that points to the method of the current controller class or global function. It can also be a method with an array name pointing to a class. Any other parameters will be passed to the renderDynamic () method. The callback will return dynamic content instead of simply displaying it.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.