Yii 2 在 yii\caching 命名空間提供統一介面 Cache,所有具體驅動繼承自 Cache,業務代碼零修改即可切換後端。
| 組件類 | 底層存儲 | 適用場景 | 依賴擴展 |
|---|---|---|---|
ApcCache | APCu | 單機高性能、OpCode 緩存共存 | apcu |
DbCache | 資料庫表 (預設 SQLite) | 無額外服務、數據持久化需求 | PDO |
FileCache | 文件系統 | 大塊數據、頁面緩存、跨部署簡單 | 無 |
MemCache | Memcached | 分佈式、高併發、會話共享 | memcached |
RedisCache (yii2-redis) | Redis | 豐富數據結構、發布訂閱、持久化 | redis + yii2-redis |
XCacheCache | XCache | 舊項目兼容 | xcache |
ZendDataCache | Zend Server Data Cache | Zend Server 環境 | Zend Server |
DummyCache | 空實現 | 開發/測試環境禁用緩存 | 無 |
// config/main.php
'components' => [
'cache' => [
'class' => 'yii\caching\MemCache',
'servers' => [
['host' => '10.0.1.10', 'port' => 11211, 'weight' => 60],
['host' => '10.0.1.11', 'port' => 11211, 'weight' => 40],
],
'keyPrefix' => 'myapp_', // 多應用隔離
],
],
$cache = Yii::$app->cache;
// 寫入,30 秒過期
$cache->set('user:1001', $userProfile, 30);
// 讀取
$profile = $cache->get('user:1001');
if ($profile === false) {
$profile = $this->fetchFromDb(1001);
$cache->set('user:1001', $profile, 30);
}
// 批量讀取 (MemCache/Redis 支援原生 mget)
$profiles = $cache->mget(['user:1001', 'user:1002']);
// 刪除
$cache->delete('user:1001');
// 清空 (謹慎!影響所有應用)
$cache->flush();
<?php if ($this->beginCache('article-'.$model->id, [
'duration' => 3600,
'dependency' => [
'class' => 'yii\caching\DbDependency',
'sql' => 'SELECT MAX(updated_at) FROM article WHERE id = '.$model->id,
],
'variations' => [Yii::$app->language], // 按語言區分
])): ?>
<div class="article">
<h1><?= $model->title ?></h1>
<div><?= $model->content ?></div>
</div>
<?php $this->endCache(); ?>
支援嵌套:外層緩存整頁佈局,內層緩存評論列表,內層過期不影響外層有效數據。
public function behaviors() {
return [
'pageCache' => [
'class' => 'yii\filters\PageCache',
'only' => ['index', 'view'],
'duration' => 600,
'variations' => [
Yii::$app->language,
Yii::$app->request->get('page'),
],
'dependency' => [
'class' => 'yii\caching\DbDependency',
'sql' => 'SELECT MAX(updated_at) FROM post',
],
],
];
}
FileDependency、DbDependency、ExpressionDependency、ChainedDependency 實現智能失效。$this->renderDynamic('renderUserPanel') 在片段/頁面緩存中插入實時渲染區塊(如用戶名、購物車數量)。Yii::$app->cache['key'] = $value / $value = Yii::$app->cache['key'],得益於 ArrayAccess 實現。FileCache 或 ApcCache。MemCache。RedisCache (via yiisoft/yii2-redis)。DummyCache 避免干擾調試。