Example of caching usage of YII Framework Framework tutorial _php

Source: Internet
Author: User
Tags apc getting started with php session id smarty template
The examples in this article describe the YII framework cache usage. Share to everyone for your reference, as follows:

The cause of the cache is well known. So yii as an efficient, easy-to-use framework, cannot but support caching. So Yii provides an interface to all popular caches, and you can use different caches depending on your needs.

Introduction to Caching in 1.YII

The cache in Yii is defined by the component, 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 is explained as follows:

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

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 cache 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 caching. In the next level, we store a page fragment 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'll explain in detail how to use caching at 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 the cache as a persistent memory. (for example, do not use the cache to store Session data).

2. How the cache is configured and invoked

The caches in Yii are mainly implemented by components, and they need to be configured in a cached class description.

Typically the 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 (*         Array (*           ' host ' = ' server1 ', *           ' port ' =>11211,*           ' weight ' =>60,*         ), *         Array ( *           ' host ' = ' server2 ', *           ' port ' =>11211,*           ' weight ' =>40,*         ),   *), *), *) ,* )

How to use:

Yii encapsulates methods for different cache operations, mainly focused on CCache. CCache is the base class for all cache classes. So it's simple to configure the cache so that it can be called:

<?php/** * CCache is the base class for cache classes with different cache storage implementation. * * A data item can be stored in the cache by calling {@link set} and is retrieved back * later by {@link get}. In both operations, a key identifying the data item is required. * An 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} would not * return the data item. * * Note, by definition, cache does not ensure the existence of a value * even if it does not expire. Cache is isn't meant to be a persistent storage.  * * CCache implements the interface {@link ICache} with the following methods: *
 
 
      *
    • {@link Get}: Retrieve the value with a key (if any) from cache
    • *
    • {@link Set}: Store the value with a key into cache
    • *
    • {@link Add}: Store the value only if the cache does not has this key
    • *
    • {@link Delete}: Delete the value with the specified key from the cache
    • *
    • {@link Flush}: Delete all values from cache
    • *
* * Child classes must implement the following methods: *
      *
    • {@link GetValue}
    • *
    • {@link SetValue}
    • *
    • {@link AddValue}
    • *
    • {@link DeleteValue}
    • *
    • {@link Flush} (optional)
    • *
* * CCache also implements arrayaccess so the it can be used as an array. * * @author Qiang Xue * @version $Id: ccache.php 3001 2011-02-24 16:42:44z alexander.makarow $ * @package system.caching * @since 1.0 */a Bstract class CCache extends Capplicationcomponent implements ICache, arrayaccess{

As you can see from the CCache class description, a common method of caching operations Get,set,add,delete,flush

/** * Retrieves a value from the 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 no T in the cache, expired or the dependency have changed. */public function Get ($id) {if ($value = $this->getvalue ($this->generateuniquekey ($id)))!==false) {$data =    Unserialize ($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 perform Ance since it reduces the communication cost. * In case a of cache doesn ' t support this feature natively, it'll be the simulated by the 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 would be Replaced with the new ones. * * @param string $id The key identifying the value to being 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 to cache, false otherwise */public function set ($id, $value, $e Xpire=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 to cache if the cache 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 being cached * @param integer $expire The number of seconds in which the cached value wil L 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 to cache, false otherwise */public function add ($id, $value, $e Xpire=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 value to be deleted * @return b Oolean If no error happens during deletion */public function Delete ($id) {yii::trace (' Deleting '. $id. ' From cache ', ' sys Tem.caching. '.  Get_class ($this)); return $this->deletevalue ($tHis->generateuniquekey ($id));} /** * Deletes all values from cache. * Be careful of performing this operation if the cache was 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 official yii of the use of several methods of caching instructions, this is insensitive, copy the

3. Cache Usage: Data 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 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 a different WEB request), it is possible to retrieve it from the cache by calling get () from the 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);}

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 be used just 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 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.

This value will expire after 30 seconds//may also be faster due to dependent file changes 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.

4. Cache Usage: Fragment caching

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.

... 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 is automatically inserted in this place; Otherwise, the contents within the IF statement are executed and cached when the Endcache () is triggered.

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:

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

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:

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

Varybyexpression:by Setting this option to a PHP expression, we can make the cached content to is variated according to T He result of 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 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:

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

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.

... Other HTML content ... <?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 (); } ..... Other HTML content ...

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.

5. Cache Usage: Page caching

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 a very similar way to filters: The tool widget (filter filters) executes before the content in the action action executes and ends after execution.

6. Cache Usage: Dynamic content

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.

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

For more information on YII related content readers can view this site topic: "YII framework Introduction and common skills Summary", "PHP Excellent Development Framework Summary", "Smarty Template Primer Basic Tutorial", "PHP date and Time usage summary", "PHP object-oriented Programming introduction Tutorial", " PHP String Usage Summary, "Getting Started with Php+mysql database operations" and "PHP Common Database Operations Skills Summary"

It is hoped that this article is helpful to the PHP program design based on 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.