A cache framework is a good framework. The following small series will introduce how to use the cache in yii2 through this article. It is of great reference value. If you are interested, you can learn it together. A good framework is definitely inseparable from the use of the cache. On the contrary, A framework without caching is certainly not a good one. It seems like a meaning. No matter what it means, let's take a look at how to use caching in yii2.
It's time for our first step. Let's configure the components first.
For convenience, our cache component is configured in the common \ config \ main. php file. First, we can simply configure the File Cache.
'components' => [ 'cache' => [ 'class' => 'yii\caching\FileCache', 'cachePath' => '@runtime/cache2', ], ],
The so-called File Cache actually stores the data we want to cache in the file. Where is the data cached?
// The default cache path is under the @ app \ runtime \ cache directory. If you want to modify the cache path, configure the cachePath as configured above.
Let's take a look at the operation.
$ Cache = Yii: $ app-> cache; $ data = $ cache-> get ('cache _ data_key '); if ($ data = false) {// here we can operate the database to obtain data, and then cache $ cacheData = ...... // The first parameter of the set method is the key value corresponding to our data, the second parameter is the data to be cached. The third parameter is the cache time. If the value is 0, the data is permanently cached. The default value is 0 $ cache-> set ('cache _ data_key ', $ cacheData, 60*60);} var_dump ($ data );
The above content is the Yii2 Cache Usage method introduced by xiaobian. You can refer to it.
The following describes how to set Cache for Yii.
Add the following in the components array:
The Code is as follows:
'Cache' => array ('class' => 'cfilecache '),
Set Cache:
Yii: app ()-> cache-> set ('testcache', array (,); // The default validity period is one year. Yii: app () -> cache-> set ('testcache', array (3600,),); // one minute, in seconds
Get Cache:
$data = Yii::app()->cache->get('testcache');
Delete a single Cache:
Yii::app()->cache->delete('testcache');
Clear all Cache:
Yii::app()->cache->flush();