yii2-redis icon indicating copy to clipboard operation
yii2-redis copied to clipboard

redis hashes as php array

Open theKerosin opened this issue 10 years ago • 7 comments

I propose to explicitly define next methods in \yii\redis\Connection

public function hSet($key, array $data);
public function hMset($key, array $data);
public function hGetAll($key);

To work with redis hashes as php associative arrays e.g.

#set
$redis->hMset('someKey', ['hello' => 'world', 'someKey' => 'someValue']);
#get
$redis->hGetAll('someKey');
#return ['hello' => 'world', 'someKey' => 'someValue'], instead of  ['hello', 'world', 'someKey', 'someValue']

theKerosin avatar Oct 13 '15 22:10 theKerosin

Good idea. @cebe would it break BC?

samdark avatar Oct 13 '15 22:10 samdark

And not only hashes - zrange, zrevrange .etc with options WITHSCORES too

        $redis->executeCommand('ZREVRANGE',['myzset', 0, 2, 'WITHSCORES']);
        #return ['value1',5,'value2',4]   best expected ['value1'=>5, 'value2'=>4]

Insolita avatar Nov 15 '15 04:11 Insolita

Not completely clear but it may be implemented as separate method

theKerosin avatar Jan 25 '16 19:01 theKerosin

this will break existing magic methods.

cebe avatar Mar 01 '16 03:03 cebe

public function hSet($key, array $data); It is recommended to public function hSet($key, $data, $value = ''); to compatible $redis->hSet('somekey','field','value');

lyt8384 avatar Dec 01 '16 00:12 lyt8384

Hi, all~ You may simply add a helper function in your extended ArrayHelper etc.

    /**
     * post process for redis hgetall, rebind the key-value relation
     * @param array $arr
     * @param array $decodeFileds the filed names need json_decode
     * @return NULL|[]
     * @author xieyh
     */
    public static function postRedisHgetall($arr, $decodeFileds = null) {
        if(empty($arr)) return null;
        $cnt = count($arr);
        $data = [];
        for($i = 0; $i < $cnt; $i += 2){
            $filed = $arr[$i];
            $value = $arr[$i+1];
            if($decodeFileds && in_array($filed, $decodeFileds)){
                $value = json_decode($value, TRUE);
            }
            $data[$filed] = $value;
        }
        return $data;
    }

yanhuixie avatar Apr 16 '19 04:04 yanhuixie

The feature of returning associative array is useful.

curtis18 avatar Sep 17 '19 03:09 curtis18