Dragonfly

Redis XADD with PHP (Detailed Guide w/ Code Examples)

Use Case(s)

The XADD command in Redis is used to append new entries to a stream. This is especially useful in tracking activities or events where chronological order and data persistence are needed, such as user activity logs, IoT sensor data, real-time analytics, etc.

Code Examples

First, you need to make sure you have the Predis client installed for PHP. If not, you can use composer:

composer require predis/predis

Here's an example of how to use XADD with PHP:

```php
require 'vendor/autoload.php';

$client = new Predis\Client();

// Add an event to the stream 'mystream'
$client->xadd('mystream', '*', ['temperature' => 22.5, 'humidity' => 60]);

```

In this example, we're adding an entry to the 'mystream' stream. The '*' argument tells Redis to assign an automatic ID to this entry. The array that follows includes the fields and their respective values in the stream entry.

Best Practices

Common Mistakes

FAQs

Q: Can I use my own ID when adding entries to a stream?

A: Yes, you can specify your own ID as long as it follows the format of a millisecond timestamp plus a sequence number (like 1518951480106-0). However, it's generally simpler and safer to let Redis auto-generate the ID using '*'.

Q: What happens if I try to add an entry to a non-existing stream?

A: If a specified stream does not exist, Redis will automatically create it when you try to add an entry. This feature allows streams to be used without explicit prior creation.

Was this content helpful?

Similar Code Examples

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Switch & save up to 80% 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost