Files
yusheng-php/application/common/library/token/driver/Cache.php
2025-12-24 16:41:01 +08:00

132 lines
3.0 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
// 文件路径application/common/library/token/driver/Cache.php
namespace app\common\library\token\driver;
use think\Cache as Caches;
/**
* Token缓存驱动
*/
class Cache
{
/**
* @var array 配置参数
*/
protected $options = [];
/**
* @var Cache 缓存实例
*/
protected $cache;
/**
* 构造函数
* @param array $options 配置参数
*/
public function __construct($options = [])
{
$this->options = $options;
// 获取缓存配置
$cacheName = isset($options['cache']) ? $options['cache'] : 'cache';
$cacheConfig = config($cacheName);
// 初始化缓存实例
$this->cache = Caches::connect($cacheConfig ?: []);
}
/**
* 获取Token
* @param string $token Token标识
* @return array|false
*/
public function get($token)
{
if (!$token) {
return false;
}
$key = $this->getCacheKey($token);
$data = $this->cache->get($key);
if (!$data) {
return false;
}
// 检查是否过期
if (isset($data['expire_time']) && $data['expire_time'] < time()) {
$this->delete($token);
return false;
}
return $data;
}
/**
* 设置Token
* @param string $token Token标识
* @param mixed $user_id 用户ID
* @param int $expire 过期时间(秒)
* @return bool
*/
public function set($token, $user_id, $expire = 0)
{
if (!$token) {
return false;
}
$data = [
'token' => $token,
'user_id' => $user_id,
'expire_time' => $expire > 0 ? time() + $expire : 0,
'create_time' => time(),
];
$key = $this->getCacheKey($token);
if ($expire > 0) {
return $this->cache->set($key, $data, $expire);
} else {
return $this->cache->set($key, $data);
}
}
/**
* 删除Token
* @param string $token Token标识
* @return bool
*/
public function delete($token)
{
if (!$token) {
return false;
}
$key = $this->getCacheKey($token);
return $this->cache->rm($key);
}
/**
* 清除用户的所有Token
* @param mixed $user_id 用户ID
* @return bool
*/
public function clear($user_id)
{
// 注意缓存驱动可能无法直接按用户ID清理所有Token
// 如果需要此功能建议使用Redis驱动或在业务层维护Token列表
// 这里简单实现,实际项目中可能需要更复杂的逻辑
return true;
}
/**
* 获取缓存键名
* @param string $token Token标识
* @return string
*/
protected function getCacheKey($token)
{
$prefix = isset($this->options['prefix']) ? $this->options['prefix'] : 'fastadmin:token:';
return $prefix . $token;
}
}