Php-yii Framework Cache Knowledge Collection

Source: Internet
Author: User
Tags apc set time yii
Yii is a high-performance PHP5 Web application Development framework. With a simple command-line tool, YIIC can quickly create a code framework for a Web application, and developers can add business logic based on the generated code framework to quickly complete application development. Caching is a simple and effective way to improve the performance of your website. A slightly larger site can be used to store relatively static data to the cache, so that we eliminate the time it takes to query and generate the data from the database, thereby improving the performance of the site by reducing the pressure on the database. Yii as a powerful PHP open source framework, and then cache this block, yii to a variety of popular caches are provided interface, we can use different caches according to the actual needs.

Yii's cache-related components are stored in the Yii/framework/caching directory, and by looking at the directory, we can see which caches are supported by Yii. Below we do some simple introduction to the relevant documents:

Cmemcache: Use PHP memcache extensions.

Capccache: Use the PHP APC extension.

Cxcache: Use PHP XCache extensions. Note that this is supported starting from version 1.0.1.

Ceacceleratorcache: Use PHP eaccelerator extensions.

Cdbcache: Use a data table to store cached data. By default, it creates and uses a SQLite3 database in the runtime directory. You can also specify a database to use for it by setting its ConnectionID property.

Czenddatacache: Use Zend Data cache as the background cache medium. Note that this is supported starting from version 1.0.4.

CFileCache: Use file storage to cache data. This is especially useful for storing large chunks of data (such as pages). Note that this is supported starting from version 1.0.6.

Cdummycache: Currently, the dummy cache does not implement caching capabilities. The purpose of this component is to simplify the code that needs to check the availability of the cache. For example, we can use this cache component during the development phase or when the server has not yet supported the actual caching functionality. When the actual cache support is enabled, we can switch to using the appropriate cache component. In both cases, we can use the same Code Yii::app ()->cache->get ($key) to get the data fragments without worrying about Yii::app ()->cache may be null. This component starts with support from version 1.0.5.

Tip: Since all of these cache components inherit from the same base class CCache, you can switch to using a different caching method without changing the code that uses the cache.

The use of caching in Yii primarily includes configuration and access to the cache components. Here are two instructions for using the Memcache cache component and the file cache component, respectively:

(1) Memcache Cache Example:

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

Array (... ' Components ' =>array ' Phpernote_cache ' =>array (' class ' = ' System.caching.CMemCache ', ' Servers ' =>array (Array (' host ' = ' ', ' Port ' =>11211, ' weight ' =>60), Array (' host ' = = ') ', ' Port ' =>11211, ' weight ' =>40),),),);

When the program is running, the cache component can be accessed through the 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. Adding cache configuration information in config file

Array (... ' Components ' =>array ' cache ' =>array (' class ' = ' System.caching.CFileCache ', ' Directorylevel ' =>2),),);

In the above configuration, the Directorylevel setting is the directory depth of the cache file, if the cache page is very large, this value needs to be set to a larger point, otherwise there will be a lot of pages in 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 the class used to process the cache, if only ' Coutputcache ', all actions in the controller are filtered through the cache, defining ' Coutputcache + post, List ', which means that only the following methods are cached: Actionpost, actionlist.

Duration is the time of the cache, the unit is the seconds,

VaryByParam is to specify a list of get parameter names, use the corresponding values to determine the version of the cached content, that is, the same action is used to distinguish between different pages of the parameters, here I use the ID and page to distinguish between different pages.

In addition to VaryByParam, other conditions can be used to differentiate pages:

Varybyexpression: Specifies that cached content varies with the result of a custom PHP expression

Varybyroute: Specifies that cache content varies based on request routing (Controller and action)

Varybysession: Specifies whether to cache the content. varies by user session

Dependency ' Specify cache invalidation dependency: You can specify a file or database; This example specifies that the database relies on cdbcachedependency to determine whether the cache is invalidated by a change in the value of the data table. For example, if a new record is added to the table, even if the cache is over 5 minutes (<3600), it will still be judged as invalid, thus querying the database, generating the entire page, and caching again;

Hint: Yii can also support Redis, need to install a plugin:

The cache can be used at different levels. At the lowest level, you can use it to cache individual data (data cache). At the top level, we cache a page fragment (fragment cache) generated by the view script. At the highest level, the entire page can be stored so that it is read directly from the cache when needed. This paper describes the configuration and implementation of page caching;

Data caching

The data cache stores some PHP variables in the cache and then pulls them out of the cache. For this purpose, the base class of the cache component CCache provides the two most 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); The cached data will remain in the cache until it is purged due to certain caching policies (such as cache space is full and old data is deleted). To change this behavior, we can provide an expiration parameter when the set () is called, so that after the set time period, the cached data is cleared:

The value $value is 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 a different WEB request), you can call get () from the cache with the ID to retrieve it. If False is returned, indicating that this value is not available in the cache, we should regenerate it.

$value =yii::app ()->cache->get ($id); if ($value ===false) {    //Because $value is not found in the cache, regenerate it,    //and cache it for later use:    //Yii::app ()->cache->set ($id, $value);}

When selecting the ID for the variable to be cached, make sure that this ID is unique to all other cached variables in the app. This ID does not need to be unique between different applications. The cache component has enough intelligence to differentiate the IDs in different apps.

Some cache memory, such as MemCache, APC, supports fetching multiple cache values in batch mode. This can reduce the overhead of getting cached data. From version 1.0.8, YII provides a new method named Mget (). It can take advantage of this feature. If the underlying cache memory does not support this feature, Mget () can still simulate implementing it.

To clear a cache value from the cache, call Delete (); To clear all the data in the cache, call Flush (). Be careful when you call Flush (), because it clears the cache from other apps at the same time.

Tip: Because CCache implements Arrayaccess, the cache component can also be used like an array. Here are a few examples:

$cache =yii::app ()->cache; $cache [' username ']= $value 1;  Equivalent to: $cache->set (' username ', $value 1), $value 2= $cache [' username '];  Equivalent to: $value 2= $cache->get (' username ');

1. Cache dependency

In addition to expiration settings, cached data may be invalidated due to changes in dependency conditions. For example, if we cache the contents of certain files and those files change, we should invalidate the cached data and read the latest content from the file instead of the cache.

We represent a dependency as an instance of a ccachedependency or its subclasses. When set () is called, we pass it along together with the data to be cached. As the following code means, this value will expire after 30 seconds, but if the dependent file changes, it is immediately invalidated:

Yii::app ()->cache->set ($id, $value, New cfilecachedependency (' FileName '));

Now if we get the $value from the cache by calling get (), the dependency will be checked and if there is a change, we will get a false value indicating that the data needs to be regenerated.

The following is a brief description of the available cache dependencies:

Cfilecachedependency: If the file's last modification time changes, it depends on the change.

Cdirectorycachedependency: If the file in the directory and its subdirectories changes, the change is dependent.

Cdbcachedependency: If the query result of the specified SQL statement changes, the change is dependent.

Cglobalstatecachedependency: If the specified global state changes, it depends on the change. The global state is a cross-request, cross-session variable in the app. It is defined by the capplication::setglobalstate ().

Cchainedcachedependency: If any dependencies in the chain change, then this dependency changes.

Cexpressiondependency: If the result of the specified PHP expression changes, it depends on the change. This class is available from version 1.0.4.

Fragment cache (Fragment Caching)

Fragment caching refers to caching a fragment of a webpage. For example, if a page shows an annual sales summary in a table, we can store this table in the cache, reducing the time that each request needs to be re-generated.

To use fragment caching, call Ccontroller::begincache () and Ccontroller::endcache () in the Controller view script. Both methods start and end of the included page content will be cached. Like data caching, we need a number to identify the cached fragment. For example, the following code if Begincache () returns false, the cached content is automatically inserted in this place; Otherwise, the contents within the IF statement are executed and cached when the Endcache () is triggered.

... <?php if ($this->begincache ($id)) {...; Cached content ... <?php $this->endcache (); } .....

1. Cache option (Caching options)

When calling Begincache (), you can provide an array consisting of cache options as a second parameter to customize the fragment cache. In fact, for convenience, the Begincache () and Endcache () methods are [Coutputcache]widget packaging. Therefore, all properties of Coutputcache can be initialized in the cache option.

Validity period (Duration)

Perhaps the most common option is duration, which specifies how long the content is valid in the cache. is a bit similar to the Ccache::set () expiration parameter. The following code caches the content fragment for up to one hour:

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

If we don't set the deadline, it will default to 60, which means the cached content will be invalid after 60 seconds.

Dependency (Dependency)

Like data caching, content fragments are cached and can be relied upon. For example, the content of an article is displayed depending on whether the article was modified.

To specify a dependency, we established the dependency option, which can be an object that implements [Icachedependency] or a configuration array that can be used to build dependent objects. The following code specifies that the fragment content depends on whether the value of the LastModified column changes:

<?php if ($this->begincache ($id, Array (' dependency ' =>array (        ' class ' = ') System.caching.dependencies.CDbCacheDependency ',        ' sql ' = ' SELECT MAX (lastmodified) from Post '))) Cached content ... <?php $this->endcache (); } ?

Change (Variation)

The contents of the cache can vary according to some parameters. For example, everyone's files are different. The cached archive content will vary according to the ID of each person. This means that when Begincache () is called, a different ID will be used.

This feature is built into the coutputcache, and programmers do not need to write patterns that change content based on their IDs. The following is a summary.

Varybyroute: Set this option to true, the cached content will vary according to the route. Therefore, the combination of each controller and action will have a separate cached content.

Varybysession: Set this option to true, the cached content will vary according to the session ID. Therefore, each user session may see different content that is provided by the cache.

VaryByParam: Sets the name of this option in the array, and the cached content is changed according to the value of the get parameter. For example, if a page shows the contents of an article based on the get parameter of the ID, we can specify VaryByParam as an array (' ID ') so that we can cache each article content. Without such a change, we can only cache an article.

Sometimes, we want the fragment cache to be enabled only for certain types of requests. For example, to display a form on a page, we only want to cache the initially requested form (via GET request). Any form that is subsequently displayed (via a 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 caches can be nested. This means that a cache fragment is attached to a larger fragment cache. For example, comments are cached in the internal fragment cache, and they are cached in the article content together in the external cache.

<?php if ($this->begincache ($id 1)) {... Externally cached content    ... <?php if ($this->begincache ($id 2)) {?>    ... Internal cached content    ... <?php $this->endcache (); } ..... Externally cached content ... <?php $this->endcache (); }?>

Nested caches can set different cache options. For example, in the example above, the internal cache and the external cache can be set to a duration of different duration values. When the data store is not valid in an external cache, the internal cache can still provide valid internal fragments. However, the reverse is not. If the external cache contains valid data, it will always keep a cached copy, even if the internal cache in the content has expired.

Page Caching

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

Page caching can be seen as a special case of fragment caching. Because Web content is often generated by applying layouts, if we simply call Begincache () and Endcache () in the layout, it will not work correctly. This is because the layout is loaded in the Ccontroller::render () method after the page content is generated.

If you want to cache the entire page, we should skip the execution of the action that generated the page content. We can use Coutputcache as an action filter to accomplish this task. The following code shows how to configure a cache filter:

Public Function Filters () {    return Array (        array (            ' Coutputcache ',            ' duration ' =>100,            ' VaryByParam ' =>array (' id '),)        ,    );}

The filter configuration above makes the filter suitable for all actions in the controller. We may limit it in one or several actions by using the plug-in operator. More details can be seen in the filter.

Tip: We can use Coutputcache as a filter because it inherits from Cfilterwidget, which means it's a tool (widget) and a filter. In fact, widgets work in much the same way as filters. Tool Widgets (filter filters) are executed before the contents of the action action are executed and end after execution.

6. Cache Usage: Dynamic content

When using fragment caching or page caching, we often encounter such situations where the output of the entire section is static except for individual places. For example, the help page might display static help information, while the user name shows the current user.

To solve this problem, we can match the cached content according to the username, but it will be a huge waste of our precious space, because the cache is the same for most other things except the user name. We can also cut pages into fragments and cache them separately, but that can complicate the page and code. A better approach is to use dynamic content functionality provided by [Ccontroller].

Dynamic content means that the fragment output is not cached even in the content that is included in the fragment cache. Even if the included content is taken out of the cache, it must be regenerated each time to make the dynamic content dynamic at all times. For this reason, we require dynamic content to be generated through some methods or functions.

Call Ccontroller::renderdynamic () to insert dynamic content where you want.

<?php if ($this->begincache ($id)) {... Cached fragment content    ... <?php $this->renderdynamic ($callback); Cached fragment content ... <?php $this->endcache (); }?>

In the above, $callback refers to a valid PHP callback. It can be either a method that points to the current controller class or a string name for a global function. It can also be an array name that points to a method of a class. Any other parameters will be passed to the Renderdynamic () method. The callback returns dynamic content instead of just displaying it.

The knowledge about YII Framework cache this article basically made a summary, I hope you can use in the work.

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