A NATS client for PHP that does not block
(php, nats, open-source) 1 min read by Bartosz Pachołek
php-nats-jetstream-client 1.0: an async-first NATS and JetStream client for PHP 8.2+, built on Amp.
PHP has long had NATS clients, but most of them block while waiting on the network. idct/php-nats-jetstream-client is async-first: it is built on Amp, so a connection, its subscriptions and JetStream calls can run side by side in one process.
What it is for
Service-to-service messaging, event processing, JetStream-backed persistence and NATS microservices, in real applications. The API is typed and high level: connection management, publish and subscribe, request and reply, reconnect handling, authentication and JetStream resource management.
A first message
use IDCT\NATS\Connection\NatsOptions;
use IDCT\NATS\Core\NatsClient;
$client = new NatsClient(new NatsOptions(servers: ['nats://127.0.0.1:4222']));
$client->connect()->await();
$ack = $client->jetStream()->publish('orders.created', '{"id":123}')->await();
echo "stored in {$ack->stream} at {$ack->seq}\n";
$client->disconnect()->await();
Every method returns an Amp future, so the same code works in a fiber-based application or, with await(), in a plain request.
Install
composer require idct/php-nats-jetstream-client
It supports every PHP version that still gets security fixes, from 8.2 up, and it is BSD 3-Clause licensed. It also powers symfony-nats-messenger and the live updates of this site.