Search code examples
phpredispredis

How to use prefix with Predis?


I'm using nrk/predis for handling Redis client in my PHP script.

I'm trying to set a prefix to all keys used in this client:

$client = new Predis\Client([
    'scheme'    => 'tcp',
    'host'      => REDIS_IP,
    'port'      => REDIS_PORT,
    'password'  => REDIS_PASS,
    'database'  => REDIS_DB,
    'prefix'    => REDIS_PREFIX
]);

And it this should work as it stated in their client configuration.

But $client->exists("mykey") returns false, and $client->exists(REDIS_PREFIX . "mykey") returns true.

Of course, my goal is to use only $client->exists("mykey").

I checked on the terminal and the key looks ok. (I've inserted the entries manually)


Solution

  • Place the prefix option in a new array as the second argument to your connection function. My guess is (after looking at the documentation you linked) that prefix does not belong in the first set of connection arguments for new Predis\Client() but in the second argument for (the options parameter).

    Change the code to this:

    $client = new Predis\Client([
        'scheme'    => 'tcp',
        'host'      => REDIS_IP,
        'port'      => REDIS_PORT,
        'password'  => REDIS_PASS,
        'database'  => REDIS_DB
    ], [
        'prefix'    => REDIS_PREFIX
    ]);
    

    This should allow you to call $client->exists('mykey'); and it will use your prefix given in REDIS_PREFIX