Yiiframework Introduction 5

Source: Internet
Author: User
Tags apc website performance
Yiiframework getting started tutorial

Yiiframework getting started tutorial 14 Cache

13. cache is a simple and effective way to improve website performance. By storing relatively static data to the cache, we can save the time to generate the data. Using Cache in yii mainly includes configuring and accessing cache components. The following application configuration specifies a memcache cache component that uses two cache servers:
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 uses the memory as the medium for storing cache; The capccache component encapsulates the php apc extension; and The cdbcache component stores cache data in the database. The following is 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. You can explicitly specify a database for it by setting the connectionid attribute. Tip: because all these cache components are extended from the same basic class ccache, you can switch between different cache components without modifying the code that uses the cache. 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 it can be 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 the cache for persistent storage (for example, do not use the cache to store session data ). I. 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 retained 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 line, we can also add an expiration parameter when calling set (), so that the data will be automatically cleared from the cache after a period of time. // Keep this value in the cache for up to 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 the returned value is false, the cache is unavailable and needs to be regenerated. $ 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 IDs are unique across applications, because the cache 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 clear the cache of other applications. 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'); besides expiration settings, cache Dependencies, the cached data will also become invalid due to changes in some dependency conditions. If We cache the content of a file and the file is updated later, 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 pass in the dependent instance together with the data to be cached. // The cache will expire 30 seconds later. // The cache may expire 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 now, the cache component checks the dependency conditions. If there is a change, we will get the false value -- the data needs to 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 state is a persistent variable across requests and sessions in an application. It is defined by capplication: setglobalstate. Cchainedcachedependency: The dependency is changed because any link in the dependency chain changes. 2. Fragment caching refers to caching a webpage segment. 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 content... begincache ($ id) {?>... Cached content... 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 cache. 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. 2. The validity period (duration) is perhaps the most common option, which specifies how long the content will be valid in the cache. It is similar to the ccache: Set () Expiration parameter. The following code caches a content segment for at most one hour:... other HTML content... begincache ($ id, array ('duration' => 3600) {?>... Cached content... endcache () ;}?>... Other HTML content... if we do not set the period, it will be 60 by default, which means the cache content will be invalid after 60 seconds. 3. Dependency is like data caching, and 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 icachedependency object 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 content... begincache ($ id, array ('dependency '=> array ('class' => 'System. caching. dependencies. cdbcachedependency ',' SQL '=> 'select max (lastmodified) from Post') {?>... Cached content... endcache () ;}?>... Other HTML content... 4. The variable content can be changed 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. 5. 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 content... begincache ($ id, array ('requesttypes '=> array ('get') {?>... Cached content... 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 comments are cached in the Internal Segment and they are cached in the article content together in the external cache .... Other HTML content... begincache ($ id1) {?>... Externally cached content... begincache ($ Id2) {?>... Content cached internally... endcache () ;}?>... Externally cached content... endcache () ;}?>... You can set different caching options for other HTML content... 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. 3. Page cache page cache refers to cache 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 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 in the ccontroller: render () method is loaded 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 executed before the content in the action is executed and ends 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 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 content... begincache ($ id) {?>... Cached fragment content... renderdynamic ($ callback);?>... Cached fragment content... 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.

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.