我知道这是一个老问题,但前几天我遇到了这个问题,在任何地方都找不到文件存储系统的解决方案。
我的用例是我希望能够根据句号分隔组的命名约定来删除。例如cache()->forget('foo') 不会删除密钥foo.bar。
它的工作方式是保存一个 json 编码的数组,其中包含您添加到文件存储中的所有键,然后当您要删除它时循环遍历,如果匹配则将其删除。这可能对您也有用,但如果不是,您的用例可以使用 cache()->getKeys() 方法,该方法现在也可以使用。
要遵循的步骤:
在您的 AppServiceProvider.php register 方法中添加以下内容:
use Illuminate\Support\Facades\Cache;
use App\Extensions\FileStore;
...
$this->app->booting(function () {
Cache::extend('file', function ($app) {
return Cache::repository(new FileStore($app['files'], config('cache.stores.file.path'), null));
});
});
然后在app 中创建一个名为Extensions 的新目录。在名为FileStore.php 的新Extensions 目录中添加一个新文件,其内容如下:
<?php
namespace App\Extensions;
class FileStore extends \Illuminate\Cache\FileStore
{
/**
* Get path for our keys store
* @return string
*/
private function keysPath()
{
return storage_path(implode(DIRECTORY_SEPARATOR, ['framework','cache','keys.json']));
}
/**
* Get all keys from our store
* @return array
*/
public function getKeys()
{
if (!file_exists($this->keysPath())) {
return [];
}
return json_decode(file_get_contents($this->keysPath()), true) ?? [];
}
/**
* Save all keys to file
* @param array $keys
* @return bool
*/
private function saveKeys($keys)
{
return file_put_contents($this->keysPath(), json_encode($keys)) !== false;
}
/**
* Store a key in our store
* @param string $key [description]
*/
private function addKey($key)
{
$keys = $this->getKeys();
// Don't add duplicate keys into our store
if (!in_array($key, $keys)) {
$keys[] = $key;
}
$this->saveKeys($keys);
}
// -------------------------------------------------------------------------
// LARAVEL METHODS
// -------------------------------------------------------------------------
/**
* Store an item in the cache for a given number of seconds.
*
* @param string $key
* @param mixed $value
* @param int $seconds
* @return bool
*/
public function put($key, $value, $seconds)
{
$this->addKey($key);
return parent::put($key, $value, $seconds);
}
/**
* Remove an item from the cache.
*
* @param string $key
* @return bool
*/
public function forget($forgetKey, $seperator = '.')
{
// Get all stored keys
$storedKeys = $this->getKeys();
// This value will be returned as true if we match at least 1 key
$keyFound = false;
foreach ($storedKeys as $i => $storedKey) {
// Only proceed if stored key starts with OR matches forget key
if (!str_starts_with($storedKey, $forgetKey.$seperator) && $storedKey != $forgetKey) {
continue;
}
// Set to return true after all processing
$keyFound = true;
// Remove key from our records
unset($storedKeys[$i]);
// Remove key from the framework
parent::forget($storedKey);
}
// Update our key list
$this->saveKeys($storedKeys);
// Return true if at least 1 key was found
return $keyFound;
}
/**
* Remove all items from the cache.
*
* @return bool
*/
public function flush()
{
$this->saveKeys([]);
return parent::flush();
}
}