PHP code example of kylin987 / webman-thinkorm-redis-cache

1. Go to this page and download the library: Download kylin987/webman-thinkorm-redis-cache library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kylin987 / webman-thinkorm-redis-cache example snippets


return [
    // 数据库缓存 store,需与 config/redis.php 里的连接名一致
    'cache_store'   => 'ormCache',
    // 缓存时间(秒)
    'cache_exptime' => 172800,
    // 空数据是否仍然缓存
    'cache_always'  => true,
];

// orm 缓存专用 redis 连接(连接名需与上面的 cache_store 一致)
'ormCache' => [
    'host'     => '127.0.0.1',
    'password' => '123456',
    'port'     => 6379,
    'database' => 5,   // 建议用独立库,与业务缓存隔离
],

class TenantUser extends \think\Model
{
    use \Kylin987\ThinkOrm\RedisCache\traits\ThinkOrmCache;

    protected $cachePk = ['tenant_id', 'user_id'];

    public static function onAfterUpdate(\think\Model $model): void
    {
        self::delCache($model);
    }

    public static function onAfterDelete(\think\Model $model): void
    {
        self::delCache($model);
    }
}

$user = TenantUser::getRedisCache(['tenant_id' => 10, 'user_id' => 20]);

// 第二个参数为 true 时删除缓存并重新查询数据库。
$user = TenantUser::getRedisCache(['tenant_id' => 10, 'user_id' => 20], true);

// 先读取完整模型再更新;组合字段变化时 delCache 会清理新旧两个键。
$user->save(['user_id' => 21]);

// 手动清理或删除记录。
TenantUser::delCache($user);
$user->delete();

//获取数据
$id = 10;
$user = User::getRedisCache($id);

//更新数据
//正常使用模型更新数据即可,也可以手动清理缓存触发后续的更新缓存
$id = 10;
$user = User::getRedisCache($id);
User::delCache($user);