Author: Bailang Source: http://www.manks.top/yii2_cache.html The copyright of this article belongs to the author, Reprinting is welcome, but this statement must be retained without the author's consent, and a link to the original text must be provided in an obvious position on the article page. Otherwise, we reserve the right to pursue legal liability.
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. Bar.
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' => [ <br /> 'cache' => [ <br /> 'class' => 'yii\caching\FileCache', <br /> 'cachePath' => '@runtime/cache2', <br /> ], <br />],
<span>所谓的文件缓存,其实就是把我们要缓存的数据存放到文件内,那数据又缓存到哪里了呢?</span>
//The default cache path is in the @appruntimecache directory. If you want to modify the cache path, you can configure cachePath as configured above
Let’s take a look directly
<span>$cache</span> = Yii::<span>$app</span>-><span>cache; </span><span>$data</span> = <span>$cache</span>->get('cache_data_key'<span>); </span><span>if</span> (<span>$data</span> === <span>false</span><span>) { </span><span>//</span><span>这里我们可以操作数据库获取数据,然后通过$cache->set方法进行缓存 </span> <span>$cacheData</span> = ...... <span>//</span><span>set方法的第一个参数是我们的数据对应的key值,方便我们获取到 //第二个参数即是我们要缓存的数据 //第三个参数是缓存时间,如果是0,意味着永久缓存。默认是0 </span> <span>$cache</span>->set('cache_data_key', <span>$cacheData</span>, 60*60<span>); } </span><span>var_dump</span>(<span>$data</span>);
Continue reading