hyperf-chat/app/Cache/Repository/AbstractRedis.php

61 lines
1.1 KiB
PHP
Raw Normal View History

2021-05-21 22:56:42 +08:00
<?php
2021-08-28 16:11:38 +08:00
declare(strict_types=1);
2021-05-21 22:56:42 +08:00
namespace App\Cache\Repository;
use Hyperf\Redis\Redis;
abstract class AbstractRedis
{
protected $prefix = 'rds';
protected $name = '';
2021-08-28 16:11:38 +08:00
/**
* 静态方法调用(获取子类实例)
*
* @return static
*/
2021-06-04 19:55:20 +08:00
public static function getInstance()
{
2021-07-23 21:34:29 +08:00
return di()->get(static::class);
2021-06-04 19:55:20 +08:00
}
2021-05-21 22:56:42 +08:00
/**
* 获取 Redis 连接
*
* @return Redis|mixed
*/
protected function redis()
{
2021-08-30 22:27:10 +08:00
return di()->get(Redis::class);
2021-05-21 22:56:42 +08:00
}
/**
* 获取缓存 KEY
*
2021-05-22 14:47:46 +08:00
* @param string|array $key
2021-05-21 22:56:42 +08:00
* @return string
*/
2021-08-28 16:11:38 +08:00
protected function getCacheKey($key = ''): string
2021-05-21 22:56:42 +08:00
{
2021-05-22 14:47:46 +08:00
$params = [$this->prefix, $this->name];
if (is_array($key)) {
$params = array_merge($params, $key);
} else {
$params[] = $key;
}
return $this->filter($params);
}
2021-08-28 16:11:38 +08:00
protected function filter(array $params = []): string
2021-05-22 14:47:46 +08:00
{
foreach ($params as $k => $param) {
2021-08-30 22:27:10 +08:00
$params[$k] = trim((string)$param, ':');
2021-05-22 14:47:46 +08:00
}
return implode(':', array_filter($params));
2021-05-21 22:56:42 +08:00
}
}