phpzend-frameworkzend-framework2zend-framework3zend-cache

Obtaining All Cache Keys in Zend-Cache


Here is my cache initialization code:

use Zend\Cache\StorageFactory;
$cache   = StorageFactory::factory(array(
                    'adapter' => array(
                            'name'    => 'filesystem',
                            // With a namespace we can indicate the same type of items
                            // -> So we can simple use the db id as cache key
                            'options' => array(
                                    'namespace' => 'dbtable',
                                    'cache_dir' => Pluto::path('cache')
                            ),
                    ),
                    'plugins' => array(
                            // Don't throw exceptions on cache errors
                            'exception_handler' => array(
                                    'throw_exceptions' => false
                            ),
                            // We store database rows on filesystem so we need to serialize them
                            'Serializer'
                    )
            ));

What Id like to know is how do I obtain all of the cache keys we have inside this cache object

For example, executing this code now:

$cache->setItem('key1','foo');

$cache->setItem('key2','bar');

$cache->setItem('key3','baz');

And executing this code at a different area/point:

$cache->setItem('key4','foo2');

$cache->setItem('key5','bar2');

$cache->setItem('key6','baz2');

I'd like an array containing ['key1','key2','key3','key4','key5','key6'] which would come presumbly from an internal array of all the keys inside the cache object (including ones that were not affected during this specific request)?


Solution

  • AFAIK, there is no method from zend-cache for retrieving all keys inside cache object. But if you wanna retrieve all keys, you can iterate the object. It is not array, but you can make it as array if you want.

    $caches = $cache->getIterator();
    $cacheKeys = []
    foreach ($caches as $key) {
        // $key is the cache key
        $cacheKeys[] = $key;
    }
    
    print_r($cacheKeys);