In-depth parsing of PHP's Yii framework cache function, YII framework _php Tutorial

Source: Internet
Author: User
Tags apc scalar yii

In-depth parsing of PHP's caching capabilities in the YII framework, YII framework


Data caching refers to storing some PHP variables in the cache and retrieving them from the cache when they are used. It is also the basis for more advanced caching features, such as query caching and content caching.

The following code is a typical data cache usage pattern. Where $cache point to the cache component:

Attempt to retrieve $data from cache $data = $cache->get ($key), if ($data = = = False) {  //$data not found in cache, recalculate its value  //store $data to cache for Next use  $cache->set ($key, $data);} $data can use it here.

Cache components

The data cache requires the caching component to provide support, which represents various cache memory, such as memory, file, and database.

Cache components are typically registered as application components so that they can be configured and accessed globally. The following code demonstrates how to configure the application component cache to use two memcached servers:

' Components ' = [  ' Cache ' = ['    class ' = ' Yii\caching\memcache ',    ' servers ' and '      =        ' Host ' = ' server1 ',        ' port ' = = 11211,        ' weight ' = +, '      [        ' host ' = ' Server2 ',        ' Port ' = 11211,        ' weight ' [=]      ,    ],],],  

You can then access the above cache components via YII:: $app->cache.

Since all cache components support the same set of APIs, it is not necessary to modify the business code that uses the cache directly to replace it with other underlying cache components, simply by reconfiguring it in the application configuration. For example, you can modify the above configuration to use Yii\caching\apccache:

' Components ' + [  ' cache ' = [    ' class ' = ' Yii\caching\apccache ',  ],],

TIP: You can register multiple cache components, and many cache-dependent classes call a component named cache (for example, Yii\web\urlmanager) by default.
Supported Cache memory

YII supports a range of cache memory, with the following overview:

    • Yii\caching\apccache: Use the PHP APC extension. This option can be considered as the fastest caching scheme in a centralized application environment (e.g., single server, no independent load balancer, etc.).
    • Yii\caching\dbcache: Stores cached data using a table of one database. To use this cache, you must create a table corresponding to the yii\caching\dbcache::cachetable.
    • Yii\caching\dummycache: Only as a cache placeholder and does not implement any real caching functionality. The purpose of this component is to simplify the code that requires query cache validity. For example, in development, if the server does not have actual cache support, configure a cache component with it. Once a real caching service is enabled, you can switch to using the appropriate cache components. You can use the same code under both conditions. Yii:: $app->cache->get ($key) attempts to retrieve data from the cache without worrying about YII:: $app->cache may be null.
    • Yii\caching\filecache: Cache data is stored using standard files. This is especially useful for caching large chunks of data, such as an entire page of content.
    • Yii\caching\memcache: Use PHP MemCache and memcached extensions. This option is considered as the fastest caching scheme in a distributed application environment (e.g. multiple servers, load balancing, etc.).
    • Yii\redis\cache: Implements a cache component based on the Redis key-value pair memory (requires support from Redis 2.6.12 and above).
    • Yii\caching\wincache: Use PHP Wincache (also refer to) extension.
    • Yii\caching\xcache: Use PHP XCache extensions.
    • Yii\caching\zenddatacache: Use Zend Data cache as the underlying cache medium.
    • Tip: You can use different cache memory in the same application. A common strategy is to use memory-based cache storage to store small, frequently used data (for example, statistics) and to store large and less commonly used data (for example, Web content) using a file-or database-based cache memory.

Cache API

All cache components have the same base class Yii\caching\cache, so the following APIs are supported:

    • Yii\caching\cache::get (): Retrieves an item of data from the cache with a specified key (key). If the item data does not exist in the cache or has expired/lapsed, the return value is false.
    • Yii\caching\cache::set (): Specifies a key for the data to be stored in the cache.
    • Yii\caching\cache::add (): If the key is not found in the cache, the specified data is stored in the cache.
    • Yii\caching\cache::mget (): Retrieves multiple items of data from the cache by specifying multiple keys.
    • Yii\caching\cache::mset (): Stores multiple items of data in the cache, one for each key.
    • Yii\caching\cache::madd (): Stores multiple items of data in the cache, one for each key. If a key already exists in the cache, the item data is skipped.
    • Yii\caching\cache::exists (): Returns a value that indicates whether a key exists in the cache.
    • Yii\caching\cache::d elete (): Deletes the corresponding value in the cache by a key.
    • Yii\caching\cache::flush (): Deletes all data in the cache.
    • Some cache memory, such as MEMCACHE,APC, supports retrieving cached values in batch mode, which saves the expense of retrieving cached data. The Yii\caching\cache::mget () and Yii\caching\cache::madd () APIs provide support for this feature. If the underlying cache memory does not support this feature, YII also simulates the implementation.

Since Yii\caching\cache implements the PHP Arrayaccess interface, the cache component can also be used as an array, here are a few examples:

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

Cache key

Each item of data stored in the cache is uniquely identified by the key. When you store a piece of data in the cache, you must specify a key for it, and the corresponding key to retrieve the data later from the cache.

You can use a string or any value as a cache key. When the key is not a string, it is automatically serialized as a string.

Defining a cache key A common strategy is to include all the determinants in an array. For example, Yii\db\schema uses the following key to store the structure information for a data table.

[  __class__,//       struct class name  $this->db->dsn,     //Data source name  $this->db->username,  // Database login user name  $name,         //table name];

As you can see, the key contains all the necessary information you need to uniquely specify a database table.

When the same cache memory is used for multiple different applications, you should specify a unique cache key prefix for each app to avoid cache key collisions. Can be implemented by configuring the Yii\caching\cache::keyprefix property. For example, you can write the following code in the application configuration:

' Components ' = [  ' Cache ' = ['    class ' = ' Yii\caching\apccache ',    ' keyprefix ' + ' MyApp ',    //Unique key prefix  ],],

To ensure interoperability, only letters and numbers can be used here.

Cache Expiration

By default, the data in the cache is persisted until it is forcibly removed by some cache policy (for example: the cache space is full and the oldest data is removed). To change this attribute, you can provide an expiration time parameter when you call Yii\caching\cache::set () to store an item of data. This parameter represents how many seconds this data can remain valid in the cache. When you call Yii\caching\cache::get () to retrieve data, the method returns False if it has expired, indicating that the data is not found in the cache. For example:

Keep the data in the cache for 45 seconds $cache->set ($key, $data,), sleep ($data = $cache->get ($key), if ($data = = = False) {  //$dat A has expired or could not be found in the cache}

Cache dependency

In addition to the timeout setting, cached data can be invalidated by the impact of cache dependencies. For example, Yii\caching\filedependency represents a dependency on a file modification time. This change in the dependency condition also means that the corresponding file has been modified. Therefore, any stale file content in the cache should be set to a stale state, and the call to Yii\caching\cache::get () should return false.

The cache dependency is represented by a derived class of yii\caching\dependency. When you call Yii\caching\cache::set () to store an item of data in the cache, you can pass an associated cache dependent object at the same time. For example:

Create a cache dependency on the Example.txt file modification time $dependency = new \yii\caching\filedependency ([' fileName ' = ' example.txt ']);// The cached data will time out after 30 seconds//If Example.txt is modified, it may also be reset to a stale state earlier. $cache->set ($key, $data, $dependency);//The cache checks to see if the data has timed out. It also checks to see if the associated dependency has changed. False is returned when any one of the conditions is met. $data = $cache->get ($key);

The following is an overview of the available cache dependencies:

    • Yii\caching\chaineddependency: If any dependency on the chain changes, it depends on the change.
    • Yii\caching\dbdependency: If the query result of the specified SQL statement has changed, it depends on the change.
    • Yii\caching\expressiondependency: If the specified PHP expression execution result changes, the dependency changes.
    • Yii\caching\filedependency: If the file's last modification time changes, it depends on the change.
    • Yii\caching\groupdependency: A cache of data is tagged to a group name, and you can set the cache of the same group name to fail all at once by calling Yii\caching\groupdependency::invalidate ().

Query cache

The query cache is a special caching feature built on top of the data cache. It is used to cache the results of database queries.

The query cache requires a yii\db\connection and a valid cache application component. The basic usage of the query cache is as follows, assuming that the $db is a yii\db\connection instance:

$duration =;   Cached query Results 60 seconds $dependency = ...; Optional cache dependent $db->begincache ($duration, $dependency);//... Execute database query here ... $db->endcache ();

As you can see, any query results in the middle of Begincache () and Endcache () will be cached. If the results of the same query are found in the cache, the query is skipped and the results are extracted directly from the cache.

Query caching can be used with ActiveRecord and DAO.

Info: Some DBMS (for example: MySQL) also supports query caching on the database server side. You can choose to use either of the query caching mechanisms. The benefit of the query cache described above is that you can specify a more flexible cache dependency and therefore may be more efficient.
Configuration

The query cache has two configuration items set through Yii\db\connection:

Yii\db\connection::querycacheduration: The validity period of the query result in the cache, expressed in seconds. If an explicit value parameter is passed when calling Yii\db\connection::begincache (), the validity period value in the configuration is overwritten.
Yii\db\connection::querycache: The ID of the Cache app component. The default is ' cache '. The query cache is valid only if a valid cache app component is set.
Restriction conditions

The query cache is not available when the query result contains a resource handle. For example, when a BLOB column is used in some DBMS, the cached result returns a resource handle for that data column.

Some cache memory has a size limit. For example, memcache limits the maximum of 1MB per piece of data. Therefore, if the size of the query results exceeds the limit, the cache will fail.

Fragment caching

Fragment caching refers to the cache of a fragment in a page's content. For example, a page displays a summary table of yearly sales, which can be cached to eliminate the time-consuming need to regenerate the table each time the request is made. Fragment caching is implemented based on the data cache.

Enable fragment caching in the view using the following structure:

if ($this->begincache ($id)) {  //... Generate Content  here ... $this->endcache ();}

Call the Yii\base\view::begincache () and Yii\base\view::endcache () methods to wrap the content generation logic. If the content is present in the cache, the Yii\base\view::begincache () method renders the content and returns false, so the content generation logic is skipped. Otherwise, the content generation logic is executed until Yii\base\view::endcache () is executed, and the resulting content is captured and stored in the cache.

As with the data cache, each fragment cache also requires globally unique $id tags.

Cache options

If you want to specify additional configuration items for the fragment cache, pass the configuration array to the second parameter of the Yii\base\view::begincache () method. Inside the framework, the array is used to configure a Yii\widget\fragmentcache widget for fragment caching.

Expiration Time (duration)

Perhaps one of the most common configuration options in fragment caching is Yii\widgets\fragmentcache::d uration. It specifies the number of seconds the content is cached. The following code caches content for up to one hour:

if ($this->begincache ($id, [' duration ' = + 3600])) {  //... Generate Content  here ... $this->endcache ();}

If this option is not set, the default is 0 and never expires.

Depend on

As with the data cache, the content of the fragment cache can be set to cache dependencies. For example, a cached article, whether it is re-cached depends on whether it has been modified.

Specify a dependency by setting Yii\widgets\fragmentcache::d the ependency option, which can be a derived class for a yii\caching\dependency class or a configuration array to create a cache object. The following code specifies a fragment cache, which depends on whether the Update_at field has been changed.

$dependency = [  ' class ' = ' yii\caching\dbdependency ',  ' sql ' = ' SELECT MAX ' (updated_at) from Post ',];if ($ This->begincache ($id, [' dependency ' = ' = $dependency])}) {  //... Generate Content  here ... $this->endcache ();}

Change

The contents of the cache may need to change depending on some parameters. For example, a WEB app that supports multiple languages, the same piece of view code may need to generate content in multiple languages. Therefore, you can set the cache to vary depending on the current language being applied.

By setting the Yii\widgets\fragmentcache::variations option to specify a change, the value of this option should be a scalar, each scalar representing a different coefficient of change. For example, setting the cache varies according to the current language and can be used with the following code:

if ($this->begincache ($id, [' Variations ' = [Yii:: $app->language]])) {  //... Generate Content  here ... $this->endcache ();}

Switch

Sometimes you may just want to open the fragment cache under certain conditions. For example, a page that displays a form may only need to be cached on the first request (via a GET request). The form that is subsequently requested by the request (via a POST request) should not use the cache because the form may contain user input. Because of this, you can use the yii\widgets\fragmentcache::enabled option to specify the cache switch as follows:

if ($this->begincache ($id, [' Enabled ' + Yii:: $app->request->isget])) {  //... Generate Content  here ... $this->endcache ();}

Cache nesting

Fragment caches can be used in a nested set. One fragment cache can be wrapped by another. For example, comments are cached in the inner layer, and the entire comment fragment is cached in the outer story. The following code shows the nested use of the fragment cache:

if ($this->begincache ($id 1)) {  //... Generate Content  here ... if ($this->begincache ($id 2, $options 2)) {    //... Generate Content    here ... $this->endcache ();  }  // ... Generate Content  here ... $this->endcache ();}

You can set different configuration items for nested caches. For example, the inner cache and the outer cache use different expiration times. Even when the data expiration of the outer cache expires, the internal cache may still provide valid fragment cache data. However, the reverse is not. If the outer fragment cache is not expired and is considered valid, it will continue to provide the same cached copy even if the inner fragment cache is invalidated. Therefore, you must handle the expiration time and dependency in the cache nesting carefully, otherwise the outer fragment is likely to return a failure data that does not meet your expectations.

The outer failure time should be shorter than the inner layer, the outer layer of the dependency should be lower than the inner layers to ensure that the smallest fragment, the return of the latest data.
Dynamic content

When using fragment caching, you may encounter a situation where there is a little dynamic content in a large section of more static content. For example, a page header that displays the menu bar and the current user name. Another possibility is that the cached content may contain PHP code (such as the code that registers the resource bundle) that each request needs to execute. Both of these issues can be resolved using dynamic content functionality.

Dynamic content means that the content of this part of the output should not be cached, even if it is wrapped in the fragment cache. To keep the content dynamic, PHP code generation is executed for each request, even if the code is already cached.

You can call Yii\base\view::renderdynamic () in the fragment cache to insert dynamic content, as follows:

if ($this->begincache ($id 1)) {  //... Generate Content  here ... echo $this->renderdynamic (' Return Yii:: $app->user->identity->name; ');  // ... Generate Content  here ... $this->endcache ();}

The Yii\base\view::renderdynamic () method takes a section of PHP code as a parameter. The return value of the code is treated as dynamic content. This code will be executed on each request, regardless of whether the fragment cache is stored on its outer layer.

Articles you may be interested in:

    • A detailed description of the use of the front-end resource bundle in PHP's YII framework
    • Introduction to some advanced usage of caching in the YII framework of PHP
    • The use of view view in the Yii framework of PHP is advanced
    • A detailed approach to creating views and rendering views in the PHP yii framework
    • A tutorial on model models in the YII framework of PHP
    • Controller controllers in the YII framework of PHP
    • The method of removing the binding behavior of a component in PHP's YII framework
    • The definition and binding methods of behavior in the YII framework of PHP
    • In-depth explanation of properties in the Yii framework of PHP
    • A detailed description of the installation and use of PHP's YII framework Extension

http://www.bkjia.com/PHPjc/1117069.html www.bkjia.com true http://www.bkjia.com/PHPjc/1117069.html techarticle in-depth analysis of PHP's YII framework of the cache function, YII framework data cache refers to the storage of some PHP variables in the cache, and then retrieved from the cache. It's also a more advanced caching feature ...

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