很多开发er在laravel或thinkphp开发久了以后,进阶时都会选择基于swoole的hyperf框架,
如果你习惯了原有框架的redis方法,你会发现使用hyperf非常难受,所以在这里封装常用的几个方法
写法简单明了,当然,你也可以自己照着添加适合自己的封装方法
常用命令:
set 写入缓存
get 获取缓存
del 删除缓存
pull 获取并删除缓存
remember 闭包读写缓存
add 追加缓存
1.方法封装文件
<?php
declare(strict_types=1);
namespace App\Common;
use Closure;
use Hyperf\Utils\ApplicationContext;
use Psr\SimpleCache\CacheInterface;
class Cache
{
public static function getInstance()
{
return ApplicationContext::getContainer()->get(CacheInterface::class);
}
public static function remember($key, $ttl, Closure $callback)
{
$instance = self::getInstance();
$value = $instance->get($key);
if (!is_null($value)) {
return $value;
}
$instance->set($key, $value = $callback(), $ttl);
return $value;
}
public static function set($key,$value,$ttl)
{
$instance = self::getInstance();
$instance->set($key, $value, $ttl);
return $value;
}
public static function del($key)
{
$instance = self::getInstance();
$instance->delete($key);
}
public static function pull($key)
{
$instance = self::getInstance();
$value=$instance->get($key);
$instance->delete($key);
return $value;
}
public static function add($key,$value,$ttl)
{
$instance = self::getInstance();
$values=$instance->get($key);
$return =$instance->set($key, $values.$value, $ttl);
return $return;
}
public static function __callStatic($name, $arguments)
{
return self::getInstance()->$name(...$arguments);
}
}
2.在控制器中的实际用法
use App\Common\Cache;
$value = Cache::set('a','a',60);
$value = Cache::get('a');
Cache::del('a');
$value = Cache::pull('b');
$value = Cache::remember("c",3600, function () {
return 'c';
});
$value = Cache::add('c','ba',3600);