1. Go to this page and download the library: Download utopia-php/nats library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
utopia-php / nats example snippets
use Utopia\NATS\Connection;
$conn = Connection::connect('nats://127.0.0.1:4222');
// Publish
$conn->publish('greet.world', 'Hello, World!');
// Subscribe
$conn->subscribe('greet.*', function ($msg) {
echo "Received: {$msg->data}\n";
});
// Process messages
$conn->wait();
use Utopia\NATS\Connection;
use Utopia\NATS\ConnectionOptions;
// Simple
$conn = Connection::connect('nats://127.0.0.1:4222');
// With options
$conn = Connection::connect(new ConnectionOptions(
servers: ['nats://host1:4222', 'nats://host2:4222'],
name: 'my-service',
user: 'alice',
pass: 'secret',
connectTimeout: 5.0,
allowReconnect: true,
maxReconnectAttempts: 60,
));
// From URL with credentials
$conn = Connection::connect('nats://user:[email protected]:4222');
use Utopia\NATS\Headers;
// Simple publish
$conn->publish('orders.new', '{"id": 1}');
// Publish with headers
$headers = new Headers();
$headers->set('Content-Type', 'application/json');
$headers->set('X-Trace-Id', 'abc-123');
$conn->publish('orders.new', '{"id": 1}', headers: $headers);
// Async with callback
$sub = $conn->subscribe('orders.*', function ($msg) {
echo "{$msg->subject}: {$msg->data}\n";
});
// Sync
$sub = $conn->subscribe('orders.new');
$msg = $sub->nextMessage(timeout: 5.0);
// Wildcards
$conn->subscribe('events.>', fn($msg) => handle($msg)); // multi-level
$conn->subscribe('orders.*', fn($msg) => handle($msg)); // single-level
// Queue groups (load-balanced)
$conn->queueSubscribe('tasks', 'workers', function ($msg) {
processTask($msg->data);
});
// Unsubscribe
$sub->unsubscribe();
// Auto-unsubscribe after N messages
$conn->unsubscribe($sub, maxMessages: 10);
$conn->flush(); // Ensure all messages are sent
$conn->drain(); // Gracefully close (flush + unsubscribe)
$conn->close(); // Immediate close
$conn->isConnected(); // Check status
$conn->getServerInfo()->version; // Server info
use Utopia\NATS\JetStream\StreamConfig;
use Utopia\NATS\JetStream\StorageType;
use Utopia\NATS\JetStream\RetentionPolicy;
$js = $conn->jetStream();
// Create a stream
$stream = $js->createOrUpdateStream(new StreamConfig(
name: 'ORDERS',
subjects: ['orders.>'],
storage: StorageType::File,
retention: RetentionPolicy::Limits,
maxAge: 86400.0, // 1 day in seconds
replicas: 1,
));
// Stream info
$info = $stream->info(refresh: true);
echo "Messages: {$info->state->messages}\n";
// List streams
$names = $js->getStreamNames();
// Delete
$stream->delete();
$acks = $js->publishMany([
['subject' => 'orders.new', 'data' => '{"id": 1}', 'msgId' => 'order-1'],
['subject' => 'orders.new', 'data' => '{"id": 2}', 'msgId' => 'order-2'],
]);
// The acknowledgments come back in the order the messages were given.
echo "Seq: {$acks[0]->sequence}\n";
use Utopia\NATS\JetStream\ConsumerConfig;
use Utopia\NATS\JetStream\AckPolicy;
use Utopia\NATS\JetStream\DeliverPolicy;
// Create a pull consumer
$consumer = $js->createConsumer('ORDERS', new ConsumerConfig(
name: 'order-processor',
durableName: 'order-processor',
ackPolicy: AckPolicy::Explicit,
filterSubject: 'orders.>',
deliverPolicy: DeliverPolicy::All,
));
// Fetch a batch of messages
$batch = $consumer->fetch(batch: 10, timeout: 5.0);
foreach ($batch as $msg) {
echo "Processing: {$msg->getData()}\n";
$msg->ack(); // Acknowledge
// $msg->nak(); // Negative ack (redeliver)
// $msg->term(); // Terminate (no redeliver)
// $msg->inProgress(); // Extend ack deadline
}
// Fetch single message
$msg = $consumer->next(timeout: 5.0);
// Message metadata
$meta = $msg->metadata();
echo "Stream seq: {$meta->streamSequence}\n";
echo "Deliveries: {$meta->numDelivered}\n";
use Utopia\NATS\KeyValue\KeyValueConfig;
use Utopia\NATS\JetStream\StorageType;
$js = $conn->jetStream();
// Create a KV bucket
$kv = $js->createKeyValue(new KeyValueConfig(
bucket: 'config',
history: 5,
ttl: 3600.0, // 1 hour
storage: StorageType::File,
));
// Put
$revision = $kv->put('app.name', 'My Service');
// Get
$entry = $kv->get('app.name');
echo "{$entry->key} = {$entry->value} (rev: {$entry->revision})\n";
// Create (fails if key exists)
$revision = $kv->create('app.version', '1.0.0');
// Update with CAS (compare-and-swap)
$revision = $kv->update('app.version', '1.1.0', revision: $revision);
// Delete / Purge
$kv->delete('app.name');
$kv->purge('app.version');
// List keys
$keys = $kv->keys();
// Bucket status
$status = $kv->status();
echo "Values: {$status->values}, Bytes: {$status->bytes}\n";