How to Use Redis Datatypes in PHP Part 1

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

When it comes to storing and manipulating complex data structures in memory, Redis is the natural choice. This in-memory data structure server, or key-value store, allows you to work with structures such as maps, lists, sets and much more. In this article, we’ll look at some of these datatypes and talk about how to use Redis datatypes in PHP.

Prerequisites

Before we dive into the PHP code, let’s go over some important prerequisites that need to be in place:

  • Redis must be installed and properly configured. To see if there’s a Redis installation on your system, use the redis-cli --version command. You’ll get a result that looks something like this:
1
redis-cli 4.0.9
  • PHP must be installed and configured with Redis. If you’re not sure whether you have PHP installed on your system, use the following command to check:
1
php -v

You’ll see output that looks something like the following:

1
2
3
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.6, Copyright (c) 1998-2018 Zend Technologies
with Zend OPcache v7.3.6-1+ubuntu18.04.1+deb.sury.org+1, Copyright (c) 1999-2018, by Zend Technologies

What are Redis Datatypes?

Redis can be defined as a key-value store– this means that data in Redis is saved in the form of key-value pairs.

The following list contains some of the most frequently-used Redis datatypes:

  1. String — This common datatype is similar to the String found in PHP.
  2. List — A list can be thought of as a simple array that allows us to pop, push, shift and unshift its elements. A list’s elements are placed in order of insertion– a method known as FIFO or “first in, first out”.
  3. Hash— A hash works by mapping string fields and their respective string values. This datatype offers an effective way to represent objects.
  4. Set — Although sets can be considered similar to lists, a few key differences exist. The elements of a set appear just once, and they are not ordered.
  5. Sorted Set — A Redis sorted set has many of the same properties of a regular set, but there are a couple of important differences. A value stored in a sorted set has a score associated with it, and the members of a sorted set are ordered by score, from smallest to largest.

How to Connect PHP to a Redis Server

Now that we’re familiar with the Redis datatypes, let’s connect PHP to a Redis server using the Redis class:

1
$r = new Redis();

This code uses the Redis class to connect to Redis. The class grants us access to the Redis methods we’ll need to perform operations in Redis within PHP.

It’s important to monitor Redis connections and watch out for possible overloading, so we’ll use the RedisException class to handle this:

1
2
3
4
5
6
7
8
9
function Redis_connect($hostname, $port){
try {

$con = $r->connect($hostname, $port);
if (!$con) { throw new Exception(); }
} catch (Exception $e) {
die($e->getMessage());
}
}

This function connects to a Redis deployment and monitors for potential issues. Using this function in PHP is easy– we just call the function and supply the appropriate parameters for $hostname and $port.

1
2
3
4
5
6
7
8
9
10
11
//Connecting to Redis server on localhost
Redis_connect("127.0.0.1", 6379);


echo "Connection to server sucessfully";
echo "
"
;
//check whether server is running or not
echo "Server is running: " . $r->ping();
echo "
"
;

The results of this should look like the following:

1
2
Connection to server sucessfully
Server is running: +PONG

Using Getters and Setters in Redis

In addition to understanding the Redis datatypes and knowing how to connect to a Redis instance, it’s also important to be familiar with commands such as GET, SET and EXISTS.

  • GET: This command returns a value at a given key.
  • SET: This will set the string value of a key. If a value already exists for a key, this command will overwrite it.
  • EXISTS: This command checks if a specified key exists or not.

These commands allow you to retrieve, store and check data from Redis. We can use the Predis class to perform Redis operations using methods that have the same name as these commands.

Let’s look at the example shown below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
// like the SET command this PHP script sets message to hold the "Hi Universe" string
$r->set("message";, "Hi Universe");
echo "
"
;
// like the GET command this PHP script gets the value stored in the "key" message
$value = $r->get("message");
echo "
"
;
// As expected this will print out Hi Universe
print($value);
echo "
"
;

echo ($r->exists("message")) ? "The entity exists" : "please store a value in the message key";

The output of this will look like the following:

1
2
Hi Universe
The entity exists

Redis Lists

The next data structure we’ll examine is the list. Lists are composed of strings and are sorted by the time of their insertion. Elements can be inserted at the head or the tail of the list.

Shown below are the basic Redis commands for lists and their descriptions:

  1. LPUSH — adds an element at the beginning of the list
  2. RPUSH — adds an element at the end of the list
  3. LRANGE — gets element’s range in the list
  4. LLEN — gets the length of a particular list
  5. LPOP — removes the first element in the list and returns its value
  6. RPOP — removes the last element in the list and returns its value

Let’s take a look at some basic application of a list in PHP:

Example of LPUSH in Redis List

1
2
3
4
$redis->RPUSH("name", "Yeshua"); // [Yeshua]
$redis->RPUSH("name", "Raizel"); // [Yeshua, Raizel]
$keys = $redis->LRANGE("name",0,1);
var_dump($keys);

The result of this would look like the following:

1
array(2) { [0]=> string(6) "Yeshua" [1]=> string(6) "Raizel" }

The above result shows two entries– one with an index of [0] and one with an index of [1]. We can also see that the name “Raizel” was inserted after the element “Yeshua”.

Example of LPUSH in Redis List

As we mentioned in its description, LPUSH will add elements at the beginning of the list.

1
2
3
4
$redis->LPUSH("name", "Abi"); // [Abi, Yeshua, Raizel]
$redis->LPUSH("name", "Risa"); // [Risa, Abi, Yeshua, Raizel]
$keys = $redis->LRANGE("name",0,1);
var_dump($keys);

The result would look something like this:

1
array(4) { [0]=> string(4) "Risa" [1]=> string(3) "Abi" [2]=> string(6) "Yeshua" [3]=> string(6) "Raizel" }

Example of LPOP and RPOP in Redis List

In this example, we will remove elements from the beginning of the list using LPOP and from the end of the list using RPOP:

1
$redis->LPOP("name"); // This will delete "Risa" in the list
1
$redis->RPOP("name"); // This will delete "Raizel" in the list.

Example of LRANGE and LLEN in Redis List

Let’s look at some examples of how to use LRANGE and LLEN in PHP:

1
2
$keysname = $redis->lrange("name",0 ,2);
var_dump($keysname);

The code shown above will get all the elements in the “name” list. The results would look something like this:

1
array(3) { [0]=> string(3) "Abi" [1]=> string(6) "Yeshua" [2]=> string(6) "Raizel" } int(3)

Note that the results only include the remaining elements that remain after we performed an RPOP in the last section. The RPOP deleted the last element in the list.

1
2
$keyslength = $redis->LLEN("name");
var_dump($keys);

The code shown above gets the length, or the number of elements in the list. In this case, it should return int(3) which is three elements.

Conclusion

In this first article in our series, we covered quite a bit of territory. We introduced you to several of the most common Redis datatypes, demonstrated how to connect to a Redis server and looked at many code examples. We’ll continue learning how to use Redis datatypes with PHP in the next article, taking a closer look at this topic and examining more code examples.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.