PHP code example of okdewit / redis-datastructures

1. Go to this page and download the library: Download okdewit/redis-datastructures library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

okdewit / redis-datastructures example snippets


$cache = new IndexedCache(

    // Name, prefix where the cached objects are stored
    'colorcache',

    // A callback used to determine where the (integer) primary key can be found on the object
    fn(Color $color) => $color->id,

    // An array with secondary index definitions.
    ['color' => fn(Color $color) => $color->color]
);

class Color
{
    public int $id;
    public string $color;
}

$cache->setTimeToLive(CarbonInterval::day())
    ->setOnMiss(fn(int $id) => new Color($id, 'purple'));

$collection = new ColorCollection([
    new Color(1, 'green'),
    new Color(2, 'blue'),
    new Color(3, 'green')
]);

$cache->warm($collection);              // Flush & populate the cache
$cache->warm($collection, false);       // Do not flush, just extend the cache with missing items

$purple = new Color(4, 'purple');
$cache->put($purple); 

// Find by primary index (unique),
// O(1)
$color = $cache->find(4);
$this->assertEquals($purple, $color);

// Find by secondary index (non unique, collection),
// O(log(N)+M), equal time complexity to an SQL BTREE index.
$colorCollection = $cache->findBy('color', $color);
$this->assertEquals(2, $colorCollection->count());

// Group by secondary index
$colorCollection = $cache->groupBy('color');
$this->assertEquals(['blue', 'green', 'purple'], $colorCollection->keys());

$colorCollection = $cache->all();
$cache->flush();