A detailed example of caching usage for YII Framework tutorial _php

Source: Internet
Author: User
Tags apc flush mixed session id set time unique id smarty template yii

The example in this article describes the use of YII framework framework caching. Share to everyone for your reference, specific as follows:

The reasons for caching are well known. So yii as an efficient, easy-to-use framework, must support caching. So Yii provides an interface to all the popular caches, and you can use a different cache depending on your needs.

Introduction to Caching in 1.YII

The caching in Yii is defined by the component, which is specified in the following directory

/yii_dev/yii/framework/caching# Tree
.
├──capccache.php
├──ccache.php
├──cdbcache.php
├──cdummycache.php
├──ceacceleratorcache.php
├──cfilecache.php
├──cmemcache.php
├──cwincache.php
├──cxcache.php
├──czenddatacache.php
└──dependencies
├──ccachedependency.php
├──cchainedcachedependency.php
├──cdbcachedependency.php
├──cdirectorycachedependency.php
├──cexpressiondependency.php
├──cfilecachedependency.php
└──cglobalstatecachedependency.php

1 directory, files

The official text explains as follows:

YII provides different caching components that can store cached data in different media. For example, the Cmemcache component encapsulates the memcache extension of PHP and uses memory as the cache storage medium. The Capccache component encapsulates the PHP APC extension; The Cdbcache component stores cached data in the database. The following is a list of available cache components:

Cmemcache: Use PHP memcache extensions.

Capccache: Using the PHP APC extension.

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

Ceacceleratorcache: Use PHP eaccelerator extensions.

Cdbcache: Uses a datasheet 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 from version 1.0.4.

CFileCache: Cache data using file storage. This is especially good for storing large chunks of data (such as pages). Note that this is supported from version 1.0.6.

Cdummycache: Currently dummy cache does not implement caching functionality. The purpose of this component is to simplify the code that needs to check cache availability. For example, we can use this cache component during the development phase or when the server has not yet supported the actual caching capabilities. When 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 fragment without having to worry about Yii::app ()->cache might be null. This component is supported starting with version 1.0.5.

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

Caching can be used at different levels. At the lowest level, we use the cache to store a single piece of data, such as a variable, which we call the data cache (caching). In the next level, we store a fragment of the page generated by a portion of the view script in the cache. At the highest level, we store the entire page in the cache and retrieve it when needed.

In the next few sections, we will explain in detail how to use caching in these levels.

Note: By definition, caching is an unstable storage medium. Even if there is no timeout, it does not ensure that the cached data must exist. Therefore, do not use caching as persistent storage. (for example, do not use caching to store session data).

2. Caching configuration and how to call

The caching in Yii is implemented primarily through a component, which can be configured using a cached class description.

Typically a class that specifies the cache component

such as APC

' Cache ' =>array (
  ' class ' => ' System.caching.CApcCache '
),

Memcache may be configured in a way that

* Array (* '   components ' =>array (* '     cache ' =>array (* '       class ' => ' Cmemcache
'), *       ' servers ' =>array (
*           ' host ' => ' server1 ',
*           ' Port ' =>11211,
*           ' weight ' =>60,
*         ),
*         Array (
*           ' host ' => ' Server2 ',
*           "Port" =>11211,
*           ' weight ' =>40,
*
), *   ), *),
* )

How to use:

Yii encapsulates methods for different caching operations, mainly in CCache. CCache is the base class for all cache classes. So it's easy to call a cache after it's configured well:

<?php/** * CCache is the base class for cache classes with different cache storage. * A data item can be stored in cache by calling {@link set} and is retrieved back * later by {@link get}.
 In both operations, a key identifying the data item is required.
 * A expiration time and/or a dependency can also is specified when calling {@link set}.
 * If The data item expires or the dependency changes, calling {@link get} won't * return the data item. * * Note, by definition, cache does not ensure the existence of a value * even if it does not expire.
 The Cache is isn't meant to be a persistent storage. * CCache implements the interface {@link Icache} with the following methods: * <ul> * <li>{@link Get}: R Etrieve the value with a key (if all) from Cache</li> * <li>{@link Set}: Store the value and a key into CAC he</li> * <li>{@link Add}: Store the value only if cache does not have this key</li> * <li>{@link Delete}: Delete the value with the specified key from cache</li> * <li>{@link flush}: Delete all Val UEs from Cache</li> * </ul> * * Child classes must implement the following methods: * <ul> * <li >{@link getvalue}</li> * <li>{@link setvalue}</li> * <li>{@link addvalue}</li> * <l i>{@link deletevalue}</li> * <li>{@link Flush} (optional) </li> * </ul> * * CCache also Impl
 Ements arrayaccess So this it can be used as an array.  * * @author Qiang xue <qiang.xue@gmail.com> * @version $Id: ccache.php 3001 2011-02-24 16:42:44z alexander.makarow $ * @package system.caching * @since 1.0/Abstract class CCache extends Capplicationcomponent implements Icache, ARR

 ayaccess {

As you can see from the CCache class description, common caching action methods Get,set,add,delete,flush

/** * Retrieves a value from cache with a specified key. * @param string $id A key identifying the cached value * @return mixed the value stored in cache, False if the value is n
 OT in the cache, expired or the dependency has changed. */Public function get ($id) {if ($value = $this->getvalue ($this->generateuniquekey ($id))) {$data =un
    Serialize ($value);
    if (!is_array ($data)) return false; if (!) ( $data [1] instanceof icachedependency) | | $data [1]->gethaschanged ()] {yii::trace (' serving '. $id. ' "From cache ', ' system.caching. ')
      Get_class ($this));
    return $data [0];
return false;
 }/** * Retrieves multiple values from cache with the specified keys. * Some caches (such as Memcache, APC) allow retrieving multiple cached values at one time, * which may improve the perfor
 Mance since it reduces the communication cost.
 * In the case a cache doesn ' t support this feature natively, it'll be simulated by this method. * @param array $iDS List of keys identifying the cached values * @return array list of cached values corresponding to the specified keys.
 The array * is returned in terms of (key,value) pairs.
 * If A value is not cached or expired, the corresponding array value would be false.
  * @since 1.0.8 */Public Function mget ($ids) {$uniqueIDs =array ();
  $results =array ();
    foreach ($ids as $id) {$uniqueIDs [$id]= $this->generateuniquekey ($id);
  $results [$id]=false;
  $values = $this->getvalues ($uniqueIDs);
    foreach ($uniqueIDs as $id => $uniqueID) {if (!isset ($values [$uniqueID])) continue;
    $data =unserialize ($values [$uniqueID]); if (Is_array ($data) && (! $data [1] instanceof icachedependency) | | $data [1]->gethaschanged ())] {yii::trace (' serving '. $id. ' "From cache", ' system.caching. ')
      Get_class ($this));
    $results [$id]= $data [0];
} return $results;
 }/** * Stores A value identified by a key into cache. * If The cache already contains sucH a key, the existing value and * Expiration time is replaced with the new ones. * * @param string $id The key identifying the value to is cached * @param mixed $value The value to be cached * @param Integer $expire the number of seconds in which the cached value would expire.
 0 means never expire. * @param icachedependency $dependency Dependency of the cached item.
 If the dependency changes, the item is labeled invalid. * @return Boolean True if the value is successfully stored into cache, false otherwise/public function set ($id, $value, $expire =0, $dependency =null) {yii::trace (' saving '. $id. ' To cache ', ' system.caching. ')
  Get_class ($this));
  if ($dependency!==null) $dependency->evaluatedependency ();
  $data =array ($value, $dependency);
return $this->setvalue ($this->generateuniquekey ($id), serialize ($data), $expire);
 }/** * Stores A value identified by a key into the cache if the cache is does not contain this key. * Nothing would be done if the cache already contAins the key. * @param string $id The key identifying the value to be cached * @param mixed $value The value to be cached * @param int Eger $expire the number of seconds in which the cached value would expire.
 0 means never expire. * @param icachedependency $dependency Dependency of the cached item.
 If the dependency changes, the item is labeled invalid. * @return Boolean True if the value is successfully stored into cache, false otherwise/public function add ($id, $value, $expire =0, $dependency =null) {yii::trace (' adding '. $id. ' To cache ', ' system.caching. ')
  Get_class ($this));
  if ($dependency!==null) $dependency->evaluatedependency ();
  $data =array ($value, $dependency);
return $this->addvalue ($this->generateuniquekey ($id), serialize ($data), $expire); }/** * Deletes a value with the specified key from cache * @param string $id The key of the the ' value to be deleted * @ret Urn Boolean if no error happens during deletion/public function Delete ($id) {yii::trace (' DeLeting "'. $id. ' From cache ', ' system.caching '.
  Get_class ($this));
return $this->deletevalue ($this->generateuniquekey ($id));
 }/** * Deletes all values from cache.
 * Being careful of performing this operation if the cache is shared by multiple applications.
 * @return Boolean whether the flush operation was successful. * * Public Function flush () {yii::trace (' flushing cache ', ' system.caching. ')
  Get_class ($this));
return $this->flushvalues ();

 }

That

Yii::app ()->cache->xxx

XXX corresponds to the specific method.

For example:

$id = ' Key1 ';
$value = ' cache value ';
Yii::app ()->cache->add ($id, $value);
Var_dump (Yii::app ()->cache->get ($id));

The following is the use of several types of caching methods of the official Yii, here is insensitive, copy the

3. Caching Usage: Data caching

Data caching

The data cache stores some PHP variables in the cache and then takes them out of the cache. For this purpose, the base class CCache of the cache component provides two of the 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 remains in the cache unless it is purged because some caching policies, such as the cache space is full, and the old data is deleted. To change this behavior, we can provide an expiration parameter while invoking set (), so that after the set time period, the cached data is cleared:

The value $value is retained in the cache for up to 30 seconds
Yii::app ()->cache->set ($id, $value, 30);

Later, when we need to access this variable (in the same or different Web request), we can call get () from the cache by ID. 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);
}

To select an ID for a variable to be cached, make sure that the ID is unique to all other cached variables in the application. and between different applications, this ID does not need to be unique. The cache component has enough intelligence to distinguish between IDs in different applications.

Some cache memory, such as MemCache, APC, supports obtaining multiple cache values in bulk mode. This can reduce the overhead of getting cached data. From the 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 the implementation.

To clear a cached value from the cache, call Delete (); To clear all the data in the cache, call Flush (). Be careful when calling flush (), because it clears the cache from other applications 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 [' var1 ']= $value 1; Equivalent to: $cache->set (' var1 ', $value 1);
$value 2= $cache [' var2 ']; Equivalent to: $value 2= $cache->get (' var2 ');

1. Cache dependency

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

We represent a dependency as an instance of a ccachedependency or its subclasses. When the set () is invoked, we pass it along with the data to be cached.

This value will be invalidated after 30 seconds
//may also be faster due to changes in dependent files
Yii::app ()->cache->set ($id, $value, New Cfilecachedependency ( ' FileName '));

Now if we fetch $value from the cache by calling get (), the dependency will be checked and, if so, 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 a file in the directory and its subdirectories changes, it depends on the change.
Cdbcachedependency: If the query result of the specified SQL statement changes, it depends on the change.
Cglobalstatecachedependency: If the specified global state changes, it depends on the change. The global state is a cross request in the application, a variable that spans the session. It is defined by Capplication::setglobalstate ().
Cchainedcachedependency: This dependency changes if any dependencies in the chain change.
Cexpressiondependency: If the result of the specified PHP expression changes, it depends on the change. This class is available from version 1.0.4.

4. Cache Usage: Fragment caching

Fragment caching (Fragment Caching)

Fragment caching refers to caching a fragment of a Web page. For example, if a page displays an annual sales summary in a table, we can store the table in the cache, reducing the time that each request needs to be restarted.

To use fragment caching, call Ccontroller::begincache () and Ccontroller::endcache () in the Controller view script. The content of the pages included in both the start and end of these methods will be cached. Like data caching, we need a number to identify the cached fragment.

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

In the above, if Begincache () returns false, the cached content inserts the place automatically; Otherwise, the content within the IF statement is executed and cached when the Endcache () is triggered.

1. Caching option (Caching options)

When calling Begincache (), you can provide an array of cache options as the 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 cache options.

Validity period (Duration)

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

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

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

Dependence (Dependency)

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

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

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

Change (Variation)

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

Coutputcache has built this feature, and programmers don't need to write patterns that change content based on IDs. The following is a summary.

Varybyroute: Set this option to true, the cached content will change according to 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 change according to the session ID. Therefore, each user session may see different content provided by the cache.
VaryByParam: Sets the name in the array of this option, and the cached content is changed according to the value of the get parameter. For example, if a page displays the content of an article based on the ID's get parameter, we can specify VaryByParam as array (' ID ') so that we can cache the contents of each article. Without such a change, we can only cache an article.

Varybyexpression:by Setting this option to a PHP expression, we can make the cached content to is variated according to T His result is this PHP expression. This option has been available since version 1.0.4.
Request Types

Sometimes, we want the fragment cache to be enabled only for certain types of requests. For example, to display a form on a Web page, we just want to cache the initially requested form (through a GET request). Any form that is subsequently displayed (through a 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 ...
<?php if ($this->begincache ($id, Array (' Requesttypes ' =>array (' Get '))) {?>
... Cached content ...
<?php $this->endcache (); }?> ...
Other HTML content ...

2. Nesting cache (Nested Caching)

Fragment caching can be nested. This means that a cached fragment is attached to a larger fragment cache. For example, comments are cached in the internal fragment cache, and they are cached together in the content of the article in the external cache.

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

Nested caching can set different caching options. For example, in the above example, internal and external caching can set the duration of different lengths of time. The internal cache can still provide a valid internal fragment when the data store is not valid in the external cache. However, the opposite 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.

5. Caching Usage: page caching

Page Caching

Page caching refers to the content that caches the entire page. Page caching can occur in different places. For example, by selecting the appropriate page header, the client's browser may cache Web browsing for 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 viewed as a special case of fragment caching. Since web content is often generated by applying layouts, if we simply invoke Begincache () and Endcache () in the layout, it will not work properly. 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 produces 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 (
      ' Coutputcache ',
      ' duration ' =>100,
      ' VaryByParam ' =>array (' id '),)
  ;
}

The above filter configuration will make the filter applicable to all actions in the controller. We may limit it in one or several actions by using the plugin 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 is a tool (widget) and a filter. In fact, widgets work the same way as filters: Tool Widgets (filter filter) are executed before the contents of the action action are executed, and end after execution.

6. Use of caching: dynamic content

Dynamic content

When using fragment caching or page caching, we often encounter 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 is displayed for the current user.

To solve this problem, we can match the cached content according to the username, but this will be a huge waste of our valuable space, because the cache is the same as most other contents except the username. We can also cut the pages into pieces and cache them separately, but this makes the pages and code very complex. A better approach would be to use the dynamic content dynamics features provided by [Ccontroller].

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

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

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

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

More about Yii related content readers can view the site topics: "Yii framework Introduction and common skills Summary", "PHP Excellent Development Framework Summary", "Smarty Template Primer Tutorial", "PHP date and Time usage summary", "PHP object-oriented Programming Program", " Summary of PHP string usage, Introduction to PHP+MYSQL database operations, and a summary of PHP common database operations Tips

I hope this article will help you with the PHP program design based on the YII framework.

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.