Home > PHP Framework > YII > How to set up cache in yii2 framework

How to set up cache in yii2 framework

王林
Release: 2020-12-02 15:34:33
forward
2465 people have browsed it

How to set up cache in yii2 framework

The specific method is as follows:

(Related recommendations: yii)

First configure the components.

For convenience, our cache component is configured in the common\config\main.php file. First, let’s simply configure the file cache

'components' => [ 
    'cache' => [ 
        'class' => 'yii\caching\FileCache', 
        'cachePath' => '@runtime/cache2', 
    ], 
],
Copy after login

The default cache path is the @app\runtime\cache directory Next, if you want to modify the cache path, you can configure cachePath like the above configuration.

Let’s do it 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);
Copy after login

The above is the detailed content of How to set up cache in yii2 framework. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template