如何在Laravel 5中按键获取所有缓存项的列表? [英] How to get list of all cached items by key in Laravel 5?

查看:813
本文介绍了如何在Laravel 5中按键获取所有缓存项的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

laravel中的Cache类具有诸如get('itemKey')之类的方法来从缓存中检索项目,并记住('itemKey',['myData1','myData2']))之类的方法来将项目保存在缓存中. /p>

还有一种检查缓存中是否存在项目的方法:Cache :: has('myKey');

(使用基于文件的缓存驱动程序时)有什么方法可以获取缓存中所有项目的列表吗?

例如,可能被命名为"Cache :: all()"的东西会返回:

[
    'itemKey' => [
        'myData1',
        'myData2'
   ],
   'myKey' => 'foo'
]

我想到的唯一方法是使用Cache :: has()方法遍历所有可能的键名.即aaa,aab,aac,aad ...但是,当然,这不是解决方案.

我在描述此类功能的文档或API中看不到任何东西,但我认为相信必须存在它并不无道理.

解决方案

无法使用 Cache 门面来实现.其界面代表所有基础存储所提供的功能,并且某些存储不允许列出所有密钥.

如果您使用的是 FileCache ,则可以尝试通过直接与基础存储进行交互来实现.它没有提供所需的方法,因此您需要遍历缓存目录.由于可能需要进行大量磁盘I/O,因此效率不会太高.

要访问存储,您需要

$storage = Cache::getStore(); // will return instance of FileStore
$filesystem = $storage->getFilesystem(); // will return instance of Filesystem

$keys = [];
foreach ($filesystem->allFiles('') as $file1) {
  foreach ($filesystem->allFiles($file1) as $file2) {
    $keys = array_merge($keys, $filesystem->allFiles($file1 . '/' . $file2));
  }
}

The Cache class in laravel has methods such as get('itemKey') to retrieve items from the cache, and remember('itemKey', ['myData1', 'myData2']) to save items in the cache.

There is also a method to check if an item exists in the cache: Cache::has('myKey');

Is there any way, (when using the file-based cache driver), to get a list of all items in the cache?

For instance, something that might be named something like "Cache::all()" that would return:

[
    'itemKey' => [
        'myData1',
        'myData2'
   ],
   'myKey' => 'foo'
]

The only way I can think of doing this is to loop through all possible key names using the Cache::has() method. i.e. aaa, aab, aac, aad... but of course, this is not a solution.

I can't see anything in the documentation or the API that describes a function like this, but I don't think its unreasonable to believe that one must exist.

解决方案

There is no way to do that using Cache facade. Its interface represents the functionality that all underlying storages offer and some of the stores do not allow listing all keys.

If you're using the FileCache, you could try to achieve that by interacting with the underlying storage directly. It doesn't offer the method you need, so you'll need to iterate through the cache directory. It won't be too efficient due to a lot of disk I/O that might need to happen.

In order to access the storage, you need to do

$storage = Cache::getStore(); // will return instance of FileStore
$filesystem = $storage->getFilesystem(); // will return instance of Filesystem

$keys = [];
foreach ($filesystem->allFiles('') as $file1) {
  foreach ($filesystem->allFiles($file1) as $file2) {
    $keys = array_merge($keys, $filesystem->allFiles($file1 . '/' . $file2));
  }
}

这篇关于如何在Laravel 5中按键获取所有缓存项的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆