Yii cache sorting

Source: Internet
Author: User
Tags apc session id website performance
Document directory
  • Cache
Cache

Cache is a simple and effective way to improve website performance. By storing relatively static data to the cache for use, we can save generation
The time of the data.
Using Cache in yii mainly includes configuring and accessing cache components. The following application configuration specifies a memcache cache that uses two cache servers.
Components:

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

When running the program, you can access the cache component through yii: APP ()-> cache.
Yii provides multiple cache components to store cached data on different media. For example, the cmemcache component encapsulates the PHP memcache extension, which enables
Memory is used as the medium for storing cache. The capccache component encapsulates the php apc extension, and the cdbcache component stores cached data in the database. Lower
A brief description of various cache components:
Cmemcache: Use PHP memcache extension.
Capccache: PhP APC extension.
Cxcache: Use PHP xcache extension.
Cdbcache: uses a database table to store cached data. It creates and uses a sqlite3 database in the runtime directory by default.
Set the connectionid attribute to explicitly specify a database for use.
Tip: because all these cache components are extended from the same basic class ccache, you do not need to modify the code that uses the cache in different cache groups.
Switch between parts.
The cache can be used at different levels. At the lowest level, we use cache to store a single data. For example, a variable is called data cache.
At the upper level, We cache a page segment generated by the View Script. At the highest level, we store the entire page so that we can directly read from the cache when needed
.
Next we will explain how to use the cache at these levels.
Note: by definition, the cache is an unstable storage medium, and it does not guarantee that the cache exists-whether or not the cache expires. Therefore, do not use
Cache for persistent storage (for example, do not use the cache to store session data ).

I. Data Cache

The data cache stores some PHP variables in the cache. It will be retrieved later. The cache base class ccache provides two common methods: Set ()
And get ().
To store the variable $ value in the cache, we select a unique ID and call set () to store it:
Yii: APP ()-> cache-> set ($ id, $ value );
Cached data is kept in the cache until it is deleted due to some cache policies (for example, when the cache space is full, the oldest data is deleted ). To change this
If one row is set, an expiration parameter can be added when set () is called, so that data is automatically cleared from the cache after a period of time.
// Keep this value in cache for a maximum of 30 seconds
Yii: APP ()-> cache-> set ($ id, $ value, 30 );
When we need to access this variable later (whether it is the same Web request or not), we call get () to get it from the cache. If
If the return value is false, the cache is unavailable and needs to be generated again.

$ Value = yii: APP ()-> cache-> get ($ id); if ($ value = false) {// because it is not found in the cache, regenerate $ value // cache it for future use // yii: APP ()-> cache-> set ($ id, $ value );}

When you select an ID for a variable to be cached, make sure that the ID is unique in the application. You do not need to ensure that the ID is unique across applications because
The storage component has enough intelligence to distinguish the cache IDs of different applications.
To delete a cache value from the cache, call Delete (); to clear all the caches, call flush (). Be very careful when calling flush () because it will
The cache of other applications is also cleared.
Tip: Because ccache implements the arrayaccess interface, cache components can be used like arrays. For example:

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

Cache dependency
In addition to the expiration settings, cache data will also become invalid due to changes in some dependency conditions. If We cache the content of a file, the file will be
New, we should invalidate the copy in the cache and read the latest content from the file (rather than from the cache ).
We present a dependency as an instance of ccachedependency or its subclass. When we call set (), we call
Data is imported together.
// The cache will expire in 30 seconds
// It may also become invalid faster because the dependent files are updated.
Yii: APP ()-> cache-> set ($ id, $ value, 30, new cfilecachedependency ('filename '));
If we call get () to get $ value from the cache, the cache component checks the dependency conditions. If there is a change, we will get the false value -- Data
Must be regenerated.
The following is a brief description of available cache dependencies:
Cfilecachedependency: The dependency is changed because of the latest modification time of the file.
Cdirectorycachedependency: The dependency is changed because any file in the directory (or its subdirectory) is changed.
Cdbcachedependency: The dependency changes because the query results of the specified SQL statement change.
Cglobalstatecachedependency: The dependency changes because the specified global status value changes. The global status is cross-request and cross-session in the application.
Is defined by capplication: setglobalstate.
Cchainedcachedependency: The dependency is changed because any link in the dependency chain changes.

Ii. 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 number
The time when the request needs to be re-generated.
To use the segment cache, call ccontroller: begincache () and ccontroller: endcache () in the Controller View Script (). The two methods start
The page content included in the end 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
Cache 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 included in the cache option.
Initialization.

2. 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 Cache
Content fragment can be up to one hour:
Other HTML contents...

<? PHP if ($ this-> begincache ($ id, array ('duration' => 3600) {?>... Cached content... <? PHP $ this-> endcache () ;}?>

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

3. 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 that can be used to generate dependency objects.
Array. The following code specifies whether the content of the fragment 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...

4. 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 easing
Save content.
Varybysession: set this option to true. The cached content changes according to the session ID. Therefore, each user session may see
Different content.
Varybyparam: Set the name in the array of this option. The cached content changes according to the value of the get parameter. For example
According to the get parameter of ID, we can specify varybyparam as array ('id') so that we can cache the content of each article. If this is not the case
Changes, we can only cache a certain article.

Here are some questions to discuss:
I can call the following data correctly:

if($this->beginCache('good_list_manager',array('duration'=>3600,'varyByParam'=>array('id')))){?>{    // ... display the content to be cached here   $this->endCache();}

However, the following code cannot be used because the parameter 'goods [name] 'yii cannot be correctly identified!

if($this->beginCache('good_list_manager',array('duration'=>3600,'varyByParam'=>array("Goods[name]"))){    // ... display the content to be cached here   $this->endCache();}

Solution: Create a mode to change the content based on the ID.

if($this->beginCache('good_list_manager_'.$_GET[Goods][name].'_'.$_GET[Goods][bn].'_'.$_GET[Goods][cat_id].'_'.$_GET[Goods][brand_id].'_'.$_GET[Goods][marketable].'_'.$_GET[Goods][cps_status].'_'.$_GET[Goods][is_check],array('duration'=>3600))){?>{    // ... display the content to be cached here   $this->endCache();}
5. Request type (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 initially
Requested form (through 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...
6. 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 comment is cached in the internal segment, and they are
It is cached in the article content in the external cache.

Other HTML contents... <? PHP if ($ this-> begincache ($ id1) {?>... Externally cached content... <? PHP if ($ this-> begincache ($ Id2) {?>... Content cached internally... <? 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
The data stored in the external cache is invalid, and the internal cache can still provide valid internal fragments. 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.

3. 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 the appropriate page header
The browser may cache web browsing for a limited time. Web applications can also store web content in the cache. In this section, we focus on the next
Method.
Page caching can be considered as a special case of segment caching (/doc/GUIDE/caching. Fragment. 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 is
Ccontroller: The loading in the render () method is after the page content is generated.
Cache the entire page. we should skip the action that generates the page content. We can use coutputcache as the action filter.
(/Doc/GUIDE/basics. Controller # filter) to complete this task. The following code demonstrates how to configure a cache filter:

public function filters(){return array(array('system.web.widgets.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 (/doc/GUIDE/basics. Controller # 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 operation of widge is very similar to that of the filter: the tool widget (filter) is the content of the action.
Run before the row and end after execution.

4. 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 according to the user name, but this will be a huge waste of our valuable space, because the cache besides the user name
Most of the other contents are 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
The State content is dynamic at all times and 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...

Complex calling format of renderdynamic:

$ This-> renderdynamic ('widget ', 'application. Extensions. uinfo', array ('uid' => 'hahahah! '), True );
It is equivalent
$ This-> widget ('application. Extensions. uinfo', array ('uid' => 'hahahah! '), True );

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
It is a method that points to a class by an array name. Any other parameters will be passed to the renderdynamic () method. The callback will return dynamic content instead
Only show it.

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.