TL:DR 默认情况下,您需要的东西不可用,您需要自定义的包装方法,这些方法需要有关您选择的缓存驱动程序(基础技术)的“技术”知识。
Laravel 缓存支持多种技术(驱动程序),包括redis、database、file、memcached 等。所有这些驱动程序都实现相同的接口。
namespace Illuminate\Contracts\Cache;
interface Store
{
/**
* Retrieve an item from the cache by key.
*
* @param string|array $key
* @return mixed
*/
public function get($key);
/**
* Retrieve multiple items from the cache by key.
*
* Items not found in the cache will have a null value.
*
* @param array $keys
* @return array
*/
public function many(array $keys);
/**
* Store an item in the cache for a given number of minutes.
*
* @param string $key
* @param mixed $value
* @param float|int $minutes
* @return void
*/
public function put($key, $value, $minutes);
/**
* Store multiple items in the cache for a given number of minutes.
*
* @param array $values
* @param float|int $minutes
* @return void
*/
public function putMany(array $values, $minutes);
/**
* Increment the value of an item in the cache.
*
* @param string $key
* @param mixed $value
* @return int|bool
*/
public function increment($key, $value = 1);
/**
* Decrement the value of an item in the cache.
*
* @param string $key
* @param mixed $value
* @return int|bool
*/
public function decrement($key, $value = 1);
/**
* Store an item in the cache indefinitely.
*
* @param string $key
* @param mixed $value
* @return void
*/
public function forever($key, $value);
/**
* Remove an item from the cache.
*
* @param string $key
* @return bool
*/
public function forget($key);
/**
* Remove all items from the cache.
*
* @return bool
*/
public function flush();
/**
* Get the cache key prefix.
*
* @return string
*/
public function getPrefix();
}
根据您选择的驱动程序 - 您需要自定义方法来实现您的需求。
对于您的第一个问题,以下方法可用于删除多个键。
public function deleteCache(array $keys)
{
foreach ($keys as $key) {
Cache::forget($key);
}
}
我对redis很熟悉,所以我会给出一些例子。如果您打算使用redis 作为缓存驱动程序 - 最好像这样修改该方法;由于redis的delete命令支持一次删除多个key。这个比上一个更有效。
public function deleteCache(array $keys)
{
Redis::del($keys);
}
一个技巧是要小心cache prefix。如果您使用的是缓存前缀(在缓存配置文件中定义) - 那么您需要将这些前缀添加到键中。
对于您的第二个问题(使用类别删除所有缓存),有几种方法可以做到这一点,但其中一些对性能/生产不友好。在redis中,你可以执行keys或scan之类的命令来遍历数据库,然后使用返回的结果调用之前定义的方法。
尤其是keys 命令只能在生产环境中使用时格外小心。
Redis 只是示例 - 如果您要使用 database 缓存驱动程序 - 那么您需要实现方法来满足您的情况。这将需要有关 laravel 如何通过数据库(表、查询等)实现它以及您的扩展方法将如何使用它(表、查询、列、索引等)的技术知识