5

Using predis is it possible to check if a key exists?

My users data is stored as follows:

public function createUser($email, $password, $username)
{
    return $this->predis->hMset("user:{$username}", [
        'email' => $email,
        'password' => $password,
        'username' => $username
    ]);
}

Now, when I check to see if a user exists I do the following:

public function checkUserExists($username)
{
    return $this->predis->hExists("user:{$username}", 'username');
}

Is it possible to check if the user exists without having to check if the key exists? For example by just checking user:{$username}?

BugHunterUK
  • 8,346
  • 16
  • 65
  • 121
  • You can only check if the `key` exists and not the `value`. You can't check for `value` without a `key` – moh_abk Feb 04 '16 at 12:10

1 Answers1

10

Yes. Since your key is essentially just the user name, you can just see if the key exists. You can use Redis' EXISTS for this:

public function checkUserExists($username)
{
    return $this->predis->exists("user:{$username}");
}

The speed difference between the two will be very, very small, but using exists will make your code a bit cleaner.

Eli
  • 36,793
  • 40
  • 144
  • 207
  • Thanks. I ended up solving my problem a different way as I also needed to check if both email, and username, already exist (separately). I used a set for emails, and a set for username and then used exists to check Thanks. – BugHunterUK Feb 04 '16 at 21:35