Table of Contents
In addition to the expiration setting, cache Data may also become invalid due to changes in dependent 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 contents from the file rather than from the cache.
Home Backend Development PHP Tutorial Yii Framework Official Guide Supplement Series 29 - Caching: Data Caching

Yii Framework Official Guide Supplement Series 29 - Caching: Data Caching

Feb 15, 2017 am 09:15 AM



Data caching stores some PHP variables in the cache and then retrieves them from the cache later. For this purpose, the base class CCache of caching components provides the two most commonly used methods: set() and get().

To store a variable $value in the cache, we choose a unique ID and call set() to store it:


Yii::app()->cache->set($id, $value);
Copy after login

The cached data will remain in the cache unless it is cleared due to some caching policy (e.g. cache space is full, old data is deleted). To change this behavior, we can provide an expiration parameter when calling set(), so that after a set period of time, the cached data will be cleared:


// 值$value 在缓存中最多保留30秒
Yii::app()->cache->set($id, $value, 30);
Copy after login

Later when we need to access this variable (in the same or a different web request), we can call get() with the ID to retrieve it from the cache. If false is returned, it means that this value is not available in the cache and we should regenerate it.


$value=Yii::app()->cache->get($id);
if($value===false)
{
    // 因为在缓存中没找到 $value ,重新生成它 ,
    // 并将它存入缓存以备以后使用:
    // Yii::app()->cache->set($id,$value);
}
Copy after login

When selecting an ID for the variable to be cached, make sure that this ID is consistent with all other cached variables in the application. Cached variables are unique. This ID does not need to be unique between different applications. The caching component is smart enough to differentiate between IDs in different applications.

Some cache memories, such as MemCache, APC, support retrieving multiple cache values ​​in batch mode. This reduces the overhead of retrieving cached data. Starting 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 functionality, mget() can still simulate it.

To clear a cached value from the cache, call delete(); to clear all data in the cache, call flush(). Be careful when calling flush() as it will also clear caches in other applications.

Tips: Since CCache implements ArrayAccess, the cache component can also be used like an array. Here are a few examples:


##

$cache=Yii::app()->cache;
$cache['var1']=$value1;  // 相当于: $cache->set('var1',$value1);
$value2=$cache['var2'];  // 相当于: $value2=$cache->get('var2');
Copy after login

##Cache dependency

In addition to the expiration setting, cache Data may also become invalid due to changes in dependent 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 contents from the file rather than from the cache.

We represent a dependency as an instance of CCacheDependency or its subclass. When calling set() we pass it in along with the data to be cached.


// 此值将在30秒后失效
// 也可能因依赖的文件发生了变化而更快失效
Yii::app()->cache->set($id, $value, 30, new CFileCacheDependency('FileName'));
Copy after login

Now if we get

$value

from the cache by calling get(), depend on The relationship will be checked and if it has changed, 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 last modification time of the file changes, the dependency changes.
  • CDirectoryCacheDependency: If the files in the directory and its subdirectories change, the dependency changes.
  • CDbCacheDependency: If the query result of the specified SQL statement changes, the dependency changes.
  • CGlobalStateCacheDependency: If the specified global state changes, the dependency changes. Global state is a cross-request, cross-session variable in the application. It is defined through CApplication::setGlobalState().
  • CChainedCacheDependency: This dependency changes if any dependency in the chain changes.
  • CExpressionDependency: If the result of the specified PHP expression changes, the dependency changes. This class is available since version 1.0.4.
  • The above is the Yii Framework Official Guide Supplement Series 29 - Caching: the content of data caching. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Optimization strategies for data caching and memory tables in PHP and MySQL indexes and their impact on query performance Optimization strategies for data caching and memory tables in PHP and MySQL indexes and their impact on query performance Oct 15, 2023 pm 12:01 PM

Optimization strategies for data caching and in-memory tables of PHP and MySQL indexes and their impact on query performance Introduction: PHP and MySQL are a very common combination when developing and optimizing database-driven applications. In the interaction between PHP and MySQL, index data caching and memory table optimization strategies play a crucial role in improving query performance. This article will introduce the optimization strategies for data caching and memory tables of PHP and MySQL indexes, and explain their impact on query performance in detail with specific code examples.

How to choose a data caching solution suitable for PHP projects? How to choose a data caching solution suitable for PHP projects? Aug 10, 2023 pm 09:21 PM

How to choose a data caching solution suitable for PHP projects? With the rapid development of the Internet and the advent of the big data era, how to efficiently handle data access and caching has become an important issue for PHP projects. As a common performance optimization method, data caching can effectively improve the response speed and user experience of the website. However, when choosing a data caching solution suitable for PHP projects, we need to consider a series of factors, including cache type, data access mode, caching strategy, etc. This article will discuss how to choose from these aspects

Data caching and local storage experience sharing in Vue project development Data caching and local storage experience sharing in Vue project development Nov 03, 2023 am 09:15 AM

Data caching and local storage experience sharing in Vue project development In the development process of Vue project, data caching and local storage are two very important concepts. Data caching can improve application performance, while local storage can achieve persistent storage of data. In this article, I will share some experiences and practices in using data caching and local storage in Vue projects. 1. Data caching Data caching is to store data in memory so that it can be quickly retrieved and used later. In Vue projects, there are two commonly used data caching methods:

Analysis of page data caching and incremental update functions of Python implementation for headless browser collection applications Analysis of page data caching and incremental update functions of Python implementation for headless browser collection applications Aug 08, 2023 am 08:28 AM

Analysis of page data caching and incremental update functions for headless browser collection applications implemented in Python Introduction: With the continuous popularity of network applications, many data collection tasks require crawling and parsing web pages. The headless browser can fully operate the web page by simulating the behavior of the browser, making the collection of page data simple and efficient. This article will introduce the specific implementation method of using Python to implement the page data caching and incremental update functions of a headless browser collection application, and attach detailed code examples. 1. Basic principles: headless

Steps to implement web page caching and page chunking using Yii framework Steps to implement web page caching and page chunking using Yii framework Jul 30, 2023 am 09:22 AM

Steps to implement web page caching and page chunking using the Yii framework Introduction: During the web development process, in order to improve the performance and user experience of the website, it is often necessary to cache and chunk the page. The Yii framework provides powerful caching and layout functions, which can help developers quickly implement web page caching and page chunking. This article will introduce how to use the Yii framework to implement web page caching and page chunking. 1. Turn on web page caching. In the Yii framework, web page caching can be turned on through the configuration file. Open the main configuration file co

Application of queue technology in delayed message processing and data caching in PHP and MySQL Application of queue technology in delayed message processing and data caching in PHP and MySQL Oct 15, 2023 am 08:03 AM

Application of queue technology in delayed message processing and data caching in PHP and MySQL Introduction: With the rapid development of the Internet, the demand for real-time data processing is getting higher and higher. However, traditional database operation methods often cause performance bottlenecks when processing large amounts of real-time data. In order to solve this problem, queue technology came into being, which can help us implement asynchronous processing of data and improve system performance and response speed. This article will introduce the application of queue technology in delayed message processing and data caching in PHP and MySQL, and through specific code

Data caching and caching strategies for real-time chat functionality using PHP Data caching and caching strategies for real-time chat functionality using PHP Aug 25, 2023 pm 09:36 PM

Data caching and caching strategies for real-time chat function using PHP Introduction: In modern social media and Internet applications, real-time chat function has become an important part of user interaction. In order to provide an efficient real-time chat experience, data caching and caching strategies have become the focus of developers. This article will introduce data caching and caching strategies for implementing real-time chat functionality using PHP, and provide relevant code examples. 1. The role of data caching Data caching is to reduce the burden on the database and improve the response speed of the system. in live chat

How to use ECharts and php interface to implement data caching and updating of statistical charts How to use ECharts and php interface to implement data caching and updating of statistical charts Dec 17, 2023 pm 05:36 PM

How to use ECharts and php interfaces to implement data caching and updating of statistical charts. In web applications, statistical charts are often used to display data analysis results. ECharts is a popular open source JavaScript charting library that can help us create various types of interactive statistical charts. However, fetching data directly from the database and rendering charts may cause performance issues when the amount of data is very large or the data is updated frequently. In order to solve this problem, we can use the php interface to implement statistical charts

See all articles