很多人都说建议用 ThinkPHP5 的模型事件 after_write 控制缓存的创建和更新,那么如何去做呢?请贴代码,谢谢!
同时我也知道在config.php配置文件中将cache改成redis的配置
直接使用Db的方法,更新及查询的方法我知道
Db::table('think_user')->cache('user_data')->update(['id'=>1,'name'=>'thinkphp']);
Db::table('user')->cache(true)->find(1);
那么使用model 的情况下,如何进行更新缓存 和删除缓存呢,比如 $this->data($param)->save(); //新增操作
$this->save($param,['id'=>1]);//更新操作
很多人都说建议用 ThinkPHP5 的模型事件 after_write 控制缓存的创建和更新,那么如何去做呢?请贴代码,谢谢
模型中添加如下代码,可实现更新或插入前删除缓存:
protected static function init()
{
TurnGiftSetting::beforeInsert(function ($model) {
$redis = new Redis(config('redis'));
$redis->rm(self::$redisKey);
});
TurnGiftSetting::beforeUpdate(function ($model) {
$redis = new Redis(config('redis'));
$redis->rm(self::$redisKey);
});
TurnGiftSetting::beforeDelete(function ($model) {
$redis = new Redis(config('redis'));
$redis->rm(self::$redisKey);
});
TurnGiftSetting::beforeWrite(function ($model) {
$redis = new Redis(config('redis'));
$redis->rm(self::$redisKey);
});
}
protected static function init()
{
TurnGiftSetting::beforeInsert(function ($model) {
$redis = new Redis(config('redis'));
$redis->rm(self::$redisKey);
});
TurnGiftSetting::beforeUpdate(function ($model) {
$redis = new Redis(config('redis'));
$redis->rm(self::$redisKey);
});
TurnGiftSetting::beforeDelete(function ($model) {
$redis = new Redis(config('redis'));
$redis->rm(self::$redisKey);
});
TurnGiftSetting::beforeWrite(function ($model) {
$redis = new Redis(config('redis'));
$redis->rm(self::$redisKey);
});
}
温馨提示:答案为网友推荐,仅供参考