A good framework is definitely inseparable from the use of cache. On the contrary, a framework without cache is definitely not a good framework. It seems to mean the same thing. Regardless, let's first take a look at how caching is used in yii2.
It’s time for our first step again. Let’s configure the components first.
For convenience, our caching component is configured in the commonconfigmain.php file. First, let’s simply configure the file cache
'components' => [ 'cache' => [ 'class' => 'yii\caching\FileCache', 'cachePath' => '@runtime/cache2', ], ],
The so-called file cache actually means storing the data we want to cache in the file, and then caching the data. Where have you been?
//The default cache path is in the @appruntimecache directory. If you want to modify the cache path, you can configure the cachePath just like the above configuration
Let’s take a look directly
$cache = Yii::$app->cache; $data = $cache->get('cache_data_key'); if ($data === false) { //这里我们可以操作数据库获取数据,然后通过$cache->set方法进行缓存 $cacheData = ...... //set方法的第一个参数是我们的数据对应的key值,方便我们获取到 //第二个参数即是我们要缓存的数据 //第三个参数是缓存时间,如果是0,意味着永久缓存。默认是0 $cache->set('cache_data_key', $cacheData, 60*60); } var_dump($data);
The above content is small The editor introduces to you how to use Yii2 cache, you can refer to it.
The following is an introduction to how to set up the Cache cache in Yii
First add:
Copy the code to the components array of the configuration file The code is as follows:
'cache'=>array( 'class '=>'CFileCache'),
Set Cache:
Yii::app()->cache->set('testcache', array(1,3,4,6));//默认有效期为一年 Yii::app()->cache->set('testcache', array(1,3,4,6), 3600);//一个钟,秒为单位
Get Cache:
$data = Yii::app()->cache->get('testcache');
Delete single Cache:
Yii::app()->cache->delete('testcache');
Clear all Cache:
Yii::app()->cache->flush();
The above has introduced a brief analysis of the use of Yii2 cache, including yii content. I hope it will be helpful to friends who are interested in PHP tutorials.