准备数据库
-
在终端运行 mysql -u root –p
-
登录数据后,通过执行 CREATE DATABASE mystudy CHARACTER SET utf8 COLLATE utf8_general_ci; 创建一个新的数据库;
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host = localhost;dbname = mystudy',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
];
?>
第3步 - 在项目根文件夹执行:yii migrate/create test_table 。此命令将用于创建管理数据库数据库迁移。 migrations文件会出现在项目的根的 migrations 文件夹中。
<?php
use yii\db\Schema;
use yii\db\Migration;
class m160529_014611_test_table extends Migration {
public function up() {
$this->createTable("user", [
"id" => Schema::TYPE_PK,
"name" => Schema::TYPE_STRING,
"email" => Schema::TYPE_STRING,
]);
$this->batchInsert("user", ["name", "email"], [
["User1", "user11@gmail.com"],
["User2", "user22@gmail.com"],
["User3", "user33@gmail.com"],
["User4", "user44@gmail.com"],
["User5", "user55@gmail.com"],
["User6", "user66@gmail.com"],
["User7", "user77@gmail.com"],
["User8", "user88@gmail.com"],
["User9", "user99@gmail.com"],
["User10", "user1010@gmail.com"],
["User11", "user1111@gmail.com"],
]);
}
public function down() {
//$this->dropTable('user');
}
}
?>

第6步-现在,我们需要为user表创建模型。为了简便起见,我们将使用GII代码生成工具。在浏览器中打开 url: http://localhost:8080/index.php?r=gii 。
然后,点击 “Model generator” 下的 “Start”按钮。 填写表名(“user”)和模型类(“MyUser”),单击“Preview”按钮,最后点击 “Generate” 按钮。


MyUser 文件忆经生成在 models 目录。
数据缓存
-
yii\caching\DbCache − 使用一个数据库表来存储缓存数据
在yii\caching\DbCache::$cacheTable 必须指定创建一个表 -
yii\caching\ApcCache − 使用 PHP APC 扩展
-
yii\caching\FileCache − 使用文件来存储缓存数据
-
yii\caching\DummyCache − 作为高速缓存占位其中确实没有真正的缓存
这个组件的目的是为了简化检查高速缓冲存储器的可用性的代码。 -
yii\caching\MemCache − 使用 PHP memcache 扩展
-
yii\caching\WinCache − 使用PHP WinCache 扩展
-
yii\redis\Cache − 实现了基于Redis的数据库缓存组件
-
yii\caching\XCache −使用 PHP XCache 扩展
-
get() − 从缓存中检索指定键对应的数据值。如果数据值已过期/无效或者没有找到值,则将返回 false
-
add() − 如果该键没有在高速缓存中找到,则保存到缓存该键和对应的数据值
-
set() − 保存到缓存的键识别对应数据值
-
multiGet() − 从缓存中使用指定多个键检索对应多个数据值
-
multiAdd() − 在高速缓存中存储多个数据值。每个项由一个键标识。如果一个键在缓存中已经存在,则数据值将会被跳过。
-
multiSet() − 在高速缓存中存储多个数据值。每个项目由一个键来标识
-
exists() − 返回在缓存指定键是否找到对应值
-
flush() − 从缓存中删除所有的数据值
-
delete() − 通过从缓存中的关键识别移除对应数据值
-
yii\caching\DbDependency − 如果指定SQL语句的查询结果发生改变,依赖也会发生改变。
-
yii\caching\ChainedDependency − 如果链上的依赖关系发生改变,依赖也会改变。
-
yii\caching\FileDependency − 如果文件的最后修改时间发生改变,依赖也会改变。
-
yii\caching\ExpressionDependency − 如果指定PHP表达式的结果发生改变,依赖也会改变。
<?php
$params = require(__DIR__ . '/params.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' => 'xuhuhu.com',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => require(__DIR__ . '/db.php'),
],
'modules' => [
'admin' => [
'class' => 'app\modules\admin\Admin',
],
],
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
];
}
return $config;
?>
public function actionTestCache() {
$cache = Yii::$app->cache;
// try retrieving $data from cache
$data = $cache->get("my_cached_data");
if ($data === false) {
// $data is not found in cache, calculate it from scratch
$data = date("Y-m-d H:i:s");
// store $data in cache so that it can be retrieved next time
$cache->set("my_cached_data", $data, 30);
}
// $data is available here
var_dump($data);
}

查询缓存
public function actionQueryCaching() {
$duration = 10;
$result = MyUser::getDb()->cache(function ($db) {
return MyUser::find()->count();
}, $duration);
var_dump($result);
$user = new MyUser();
$user->name = "cached user name";
$user->email = "cacheduseremail@gmail.com";
$user->save();
echo "==========";
var_dump(MyUser::find()->count());
}
-
yii cache − 显示可用缓存组件
-
yii cache/flush cache1 cache2 cache3 −刷新缓存组件:cache1,cache2 和 cache3
-
yii cache/flush-all − 刷新所有缓存组件



