您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
3-1 数据缓存之增删改查
发布时间:2023-05-10 18:47:56编辑:雪饮阅读()
-
默认缓存配置
根据D:\phpstudy_pro\WWW\www.xyyii.com\basic\config\web.php中代码片段
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'aaa',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
可以看到这里默认配置的是文件缓存。
缓存的增删改查
然后缓存的增删改查其实也都是差不多的一眼就都会了。
唯一有一点就是缓存相同key名时仅第一次缓存成功。
实例如:
<?php
namespace app\controllers;
use yii\web\Controller;
class HelloController extends Controller{
//读写数据
public function actionIndex(){
$cache=\Yii::$app->cache;
//写数据
$cache->add('key1','hello world!');
//读数据
echo $cache->get('key1');
}
//修改数据
public function actionIndex2(){
$cache=\Yii::$app->cache;
//改数据
$cache->set('key1','hello world2!');
echo $cache->get('key1');
}
//删除数据
public function actionIndex3(){
$cache=\Yii::$app->cache;
//删除数据
$cache->delete('key1');
echo $cache->get('key1');
}
//清空数据-1
public function actionIndex4(){
$cache=\Yii::$app->cache;
$cache->add('key1','hello world!');
$cache->add('key2','hello world2!');
echo $cache->get('key1')."<hr/>".$cache->get('key2');
$cache->flush();
}
//清空数据-2
public function actionIndex5(){
$cache=\Yii::$app->cache;
$cache->flush();
echo $cache->get('key1')."<hr/>".$cache->get('key2');
}
//相同key写数据
public function actionIndex6(){
//相同key多次写时候,仅写成功第一次
$cache=\Yii::$app->cache;
$cache->add('key1','hello world!');
$cache->add('key1','hello world2!');
echo $cache->get('key1');
}
}
关键字词:缓存,增删改查