Lesson 4
Utilizing Redis Streams for Event Logging in PHP
Utilizing Redis Streams for Event Logging in PHP

Welcome! In this unit, we will explore how to utilize Redis streams for event logging using PHP. This is an important part of our Redis-based backend system project. By the end of this lesson, you will know how to log events and retrieve them using Redis streams. Remember, you've already learned how to manage user data and handle transactions. Now, we're adding another layer to our system by using streams.

What You'll Build

In this unit, we will focus on the following tasks:

  1. Adding Entries to a Stream: We will log user activities in a Redis stream.
  2. Reading Entries from a Stream: You will see how to read the logged events from the stream.

Let's start by refreshing what we've learned about adding data. This time, we will use streams instead of simple keys. Here's a snippet to show how you can add an entry to a stream and read it back using PHP and the Predis library:

php
1<?php 2 3require 'vendor/autoload.php'; 4 5use Predis\Client; 6 7// Connect to Redis 8$client = new Client(); 9 10// Example usage 11$streamName = 'user_activity_stream'; 12 13try { 14 $client->xadd($streamName, ['event' => 'login', 'username' => 'alice']); 15 $client->xadd($streamName, ['event' => 'login', 'username' => 'bob']); 16} catch (Exception $e) { 17 echo "Could not add entry: ", $e->getMessage(), "\n"; 18} 19 20try { 21 // supplying the count of messages as 0 for the first parameter 22 // means that we want to read all messages in the stream 23 $entries = $client->xread(0, 0, [$streamName, '0-0']); 24 foreach ($entries[$streamName] as $entry) { 25 echo "Stream entry: " . json_encode($entry) . "\n"; 26 } 27} catch (Exception $e) { 28 echo "Could not read entries: ", $e->getMessage(), "\n"; 29}

In this code, we read the entries from the user_activity_stream and print each one. The streamName and the count of entries to read help control the stream reading operation.

As a reminder for xread parameters, this is their order and meaning:

  • Count of Messages (0): This specifies the maximum number of entries to read. A value of 0 means to read all available entries.
  • Block Time (0): This is the time in milliseconds to block if no entries are available. A value of 0 means no blocking.
  • Streams and IDs ([$streamName, '0-0']):
    • $streamName: The name of the stream you want to read from.
    • '0-0': The ID from which to start reading. '0-0' means to start from the beginning of the stream.

Do you feel ready to give it a try? Let's jump into the practice section and start working on logging events using Redis streams. Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.