Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setting arrays #136

Closed
odino opened this issue Oct 2, 2013 · 2 comments
Closed

Setting arrays #136

odino opened this issue Oct 2, 2013 · 2 comments

Comments

@odino
Copy link

odino commented Oct 2, 2013

@waqasiqrar and me were looking at the set api, which doesnt allow to pass arrays.

We are converting arrays to json_encoded strings, is this the expected strategy or would you suggest anything else?

(just thinking if we're missing something)

@nrk
Copy link
Contributor

nrk commented Oct 2, 2013

Hi @odino,

as explained in #29, Predis doesn't perform any kind of serialization or deserialization of complex values as the library tries to stick with only what the commands actually do in Redis (or what the best practices described in the Redis docs say) in order to avoid unexpected or unwanted behaviours, leaving additional or more complex features to higher-level abstractions built upon the standard commands.

You can either serialize your values before passing them to set and deserialize them when fetching values back with get, or register two new virtual commands on the client such as setjson and getjson: doing so won't mess with the standard set and get commands and your code will be more self-explanatory.

Since the code in #29 is based on an older versions of Predis, I'll give you a more up-to-date snippet based on v0.8 using client options:

class StringSetJson extends Predis\Command\StringSet
{
    protected function filterArguments(Array $arguments)
    {
        $arguments[1] = json_encode($arguments[1]);
        return $arguments;
    }
}

class StringGetJson extends Predis\Command\StringGet
{
    public function parseResponse($data)
    {
        return json_decode($data, true);
    }
}

$client = new Predis\Client('tcp://127.0.0.1:6379', [
    'profile' => function ($options, $option) {
        $profile = Predis\Profile\ServerProfile::getDefault();
        $profile->defineCommand('setjson', 'StringSetJson');
        $profile->defineCommand('getjson', 'StringGetJson');

        return $profile;
    }
]);

$client->setjson("json_key", array(1,2,3,4));
$value = $client->getjson("json_key");

var_dump($value);

@nrk nrk closed this as completed Oct 2, 2013
@odino
Copy link
Author

odino commented Oct 2, 2013

thx man!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants