Welcome back to our Redis course! Now that you know how to connect to a Redis server using PHP, it's time to move forward and explore how to work with numbers. This unit builds on our previous lesson, so make sure you're comfortable with establishing a connection to a Redis server.
In this lesson, you will learn how to:
- Set numeric values.
- Retrieve and handle numeric values.
Here's the code snippet that we'll be working with:
php1<?php 2 3require 'vendor/autoload.php'; 4 5use Predis\Client; 6 7// Connect to Redis 8$client = new Client([ 9 'scheme' => 'tcp', 10 'host' => '127.0.0.1', 11 'port' => 6379, 12]); 13 14// Setting numeric values 15$client->set('count', 5); 16$client->set('completion_rate', 95.5); 17 18// Getting numeric values 19$count = $client->get('count'); 20$completionRate = $client->get('completion_rate'); 21 22echo sprintf("Course count: %d, Completion rate: %.2f\n", $count, $completionRate); 23 24?>
- We start by including the
autoload.php
from Composer to load thepredis/predis
package. - The
Predis\Client
class is used to establish a connection to the Redis server. We specify the connection parameters, such asscheme
,host
, andport
. - The
set
method in predis is used to store numeric values (count
with a value of5
andcompletion_rate
with a value of95.5
) into the Redis server. - The
get
method is used to retrieve these numeric values. Note that the values retrieved from Redis will be strings, so when displaying or using them as numbers, be sure to cast them appropriately if necessary. PHP will automatically handle the conversion when using them in numeric contexts likesprintf
. An example of casting can be seen below:
php1<?php 2 3$myString = "23"; 4echo gettype($myString)."\n"; // prints "string" 5$myNumber = (int)$myString; // casting a value as an integer 6echo gettype($myNumber)."\n"; // prints "integer" 7 8?> 9
Working with numbers in Redis is crucial because many real-world applications involve numeric data. From tracking user statistics to monitoring system performance, managing numbers in Redis allows you to perform a variety of useful operations efficiently. By mastering these basic operations, you'll be well-prepared to tackle more complex tasks and optimize your applications.
Ready to dive in? Let's move on to the practice section and get hands-on experience working with numbers in Redis!