Yii Framework cache knowledge summary_php tutorial

Source: Internet
Author: User
Tags apc website performance
Yii Framework cache knowledge summary. Yii Framework cache knowledge summary cache is a simple and effective way to improve website performance. Websites of a slightly larger scale will store relatively static data to the cache for summary of the cache knowledge of all yii frameworks.

Cache is a simple and effective way to improve website performance. Websites of a slightly larger scale will store relatively static data to the cache for the necessary time, so that we can save the time to query from the database and then generate the data, by reducing the pressure on the database, the website performance is improved.

Yii, as a powerful php open-source framework, caches this part. YII provides interfaces for various popular caches. we can use different caches as needed.

Yii cache-related components are stored in the yii/framework/caching Directory. by viewing this directory, we can know which caches yii supports. Next we will give a brief introduction to the relevant files:

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.

Using cache in Yii mainly includes configuring and accessing cache components. The following uses the memcache cache and file cache components as examples to describe them:

(1) memcache cache example:

The following application configuration specifies a memcache cache component that uses two cache servers:

array(......'components'=>array(......'phpernote_cache'=>array('class'=>'system.caching.CMemCache','servers'=>array(array('host'=>'10.201.1.101', 'port'=>11211, 'weight'=>60),array('host'=>'10.201.1.102', 'port'=>11211, 'weight'=>40),),),),);

When running the program, you can access the cache components through Yii: app ()-> phpernote_cache in the controller method. for example:

Yii: app ()-> phpernote_cache-> set ($ key, $ value, $ expire );

Yii: app ()-> phpernote_cache-> add ($ id, $ value );

Yii: app ()-> phpernote_cache-> get ($ key );

(2) file cache example:

1. add cache configuration information to the config file

array(......'components'=>array(......'cache'=>array('class'=>'system.caching.CFileCache','directoryLevel'=>2),),),);

In the preceding configuration, directoryLevel sets the directory depth of the cached file. if there are many cached pages, this value must be set to a greater value. Otherwise, there will be many pages under each directory.

2. define the filter in the controller to be cached.

public function filters(){return array(array('COutputCache + post, list','duration'=>3600,'varyByParam'=>array('id','page'),'dependency'=>array('class'=>'CDbCacheDependency','sql'=>'SELECT MAX(id) FROM phpernote_article',));}

COutputCache is a class used to process the cache. if you only specify 'coutputcache', all the actions in the controller are filtered by the cache, and 'coutputcache + post, list' is defined ', indicates that only the following methods are cached: actionPost and actionList.

Duration is the cache time in seconds,

VaryByParam specifies a list of GET parameter names and uses corresponding values to determine the cached content version. that is, the same action is used to differentiate parameters on different pages, here, I use id and page to differentiate different pages.

In addition to varyByParam, you can use other conditions to differentiate pages:

VaryByExpression: specifies that the cached content changes based on the results of a custom PHP expression.

VaryByRoute: specify that the cached content varies based on the requested route (controller and action)

VaryBySession: specifies whether the content is cached. changes due to different user sessions.

Dependency 'specifies the cache invalidation dependency: you can specify a file or database. In this example, the database depends on CDbCacheDependency. you can change the value of a data table to determine whether the cache is invalid. For example, if a new record is added to the table, even if the cache takes less than 5 minutes (<3600), it is still regarded as invalid, so as to query the database, generate the entire page, and cache it again;

Tip: yii can also support Redis, need to install a plug-in: http://www.yiibase.com/download/view/32.html

The cache can be used at different levels. At the lowest level, it can be used to cache a single data (data cache ). At the upper level, we cache a page segment (segment cache) generated by the view script ). At the highest level, you can store the entire page so that it can be directly read from the cache when needed. This article describes the page cache configuration and implementation results;

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 (for example, the cache space is full and the 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 retained for up to 30 seconds in the cache
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 ['username'] = $ value1; // equivalent to: $ cache-> set ('username ', $ value1); $ value2 = $ cache ['username']; // equivalent to: $ value2 = $ cache-> get ('Username ');

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. The following code indicates that the value will expire after 30 seconds, but will immediately expire if the dependent file changes:
 
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.

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. For 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.

......
 BeginCache ($ id) {?>... Cached content...
 EndCache () ;}?> ......

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:

......
 BeginCache ($ id, array ('duration' => 3600) {?>... Cached content...
 EndCache () ;}?> ......

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:

......
 BeginCache ($ id, array ('dependency '=> array ('class' => 'system. caching. dependencies. CDbCacheDependency ',' SQL '=> 'Select MAX (lastModified) FROM Post') {?>... Cached content...
 EndCache () ;}?> ......

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.

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:

......
 BeginCache ($ id, array ('requesttypes '=> array ('get') {?>... Cached content...
 EndCache () ;}?> ......

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.

......
 BeginCache ($ id1) {?>... Externally cached content...
 BeginCache ($ id2) {?> Contents cached inside...
 EndCache () ;}?>... Externally cached content...
 EndCache () ;}?> ......

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.

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, widgets work very similar to filters. The tool widget (filter) is executed before the content in the action is executed and ends after execution.

6. usage of cache: 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.

......
 BeginCache ($ id) {?>... Cached fragment content...
 RenderDynamic ($ callback);?>... Cached fragment content...
 EndCache () ;}?> ......

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.

Articles you may be interested in
  • Detailed analysis on the directory structure of the yii Framework
  • Mysql database cache function analysis, debugging, and Performance Summary
  • Yii Framework Yiiapp ()
  • Three solutions for ineffective page refresh caused by Js, css, and images cached on webpages
  • Php builds a simple example of its own MVC framework and provides ideas for your reference only
  • Yii database query operation summary
  • Php uses the ZipArchive function to compress and decompress files.
  • How to align check boxes (checkbox) and single-digit (radio) horizontally and vertically with the text

Caching is a simple and effective way to improve website performance. Websites of a slightly larger scale will store relatively static data to the cache for preparation...

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.