intersvyaz / yii2-tag-dependency-helper
为yii2提供统一缓存标签名称并支持失效功能的辅助工具
1.0.1
2015-06-05 08:21 UTC
Requires
- yiisoft/yii2: ~2.0.0
Requires (Dev)
- phpunit/phpunit: ~4.6.9
This package is auto-updated.
Last update: 2024-09-08 05:49:00 UTC
README
为Yii2提供统一缓存标签名称并支持失效功能的辅助工具。
使用方法
在您的模型中添加行为
... use Intersvyaz\TagDependencyHelper\Traits\CachedFind; use Intersvyaz\TagDependencyHelper\InvalidateTagBehavior; ... class Configurable extends ActiveRecord { use CachedFind; /** * @inheritdoc */ public function behaviors() { return [ [ 'class' => InvalidateTagBehavior::class, 'cache' => 'cache', // optional option - application id of cache component ], ]; } }
此行为会自动通过模型名称和模型ID对来失效标签
如果您的缓存条目需要在模型中的任何一行被编辑时刷新 - 使用 getCommonTag
辅助函数
use Intersvyaz\TagDependencyHelper\ActiveRecordCacheTags; ... $models = Configurable::getDb()->cache( function ($db) { return Configurable::find()->all($db); }, 86400, new TagDependency([ 'tags' => [ActiveRecordCacheTags::getCommonTag(Configurable::className())], ]) );
如果您的缓存条目只有在特定的模型行被编辑时才需要刷新 - 使用 getObjectTag
辅助函数
use Intersvyaz\TagDependencyHelper\ActiveRecordCacheTags; ... $cacheKey = 'Product:' . $model_id; if (false === $product = Yii::$app->cache->get($cacheKey)) { if (null === $product = Product::findOne($model_id)) { throw new NotFoundHttpException; } Yii::$app->cache->set( $cacheKey, $product, 86400, new TagDependency( [ 'tags' => [ ActiveRecordCacheTags::getObjectTag(Product::class, $model_id), ] ] ) ); }
在CachedFind特性中实现了cachedFindOne()和cachedFindAll()快捷方法,用于缓存查询。