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 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.
... <? Php if ($ this-> beginCache ($ id) {?>... Cached content... <? Php $ this-> 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:
... <? Php if ($ this-> beginCache ($ id, array ('duration' => 3600) {?>... Cached content... <? Php $ this-> 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:
... <? Php if ($ this-> beginCache ($ id, array ('dependency '=> array ('class' => 'System. caching. dependencies. CDbCacheDependency ',' SQL '=> 'select MAX (lastModified) FROM Post') {?>... Cached content... <? Php $ this-> 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:
... <? Php if ($ this-> beginCache ($ id, array ('requesttypes '=> array ('get') {?>... Cached content... <? Php $ this-> 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.
... <? 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 () ;}?> ......
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.
... <? Php if ($ this-> beginCache ($ id) {?>... Cached fragment content... <? Php $ this-> renderDynamic ($ callback);?>... Cached fragment content... <? Php $ this-> 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