AMQP publishers serialize a durable payload and route it via an exchange to a bound queue.
What It Does and When to Use It
Install php-amqplib and configure a RabbitMQ broker before using the examples. A producer publishes work, a consumer executes it, and the broker or scheduler controls delivery and retries.
Requirements, Inputs and Expected Behavior
Confirm the runtime, extension, environment variables, and permissions before running the examples in production. Use publisher confirms and durable queues when loss prevention matters.
Example 1: Basic Operation
Install php-amqplib and configure a RabbitMQ broker before using the examples.
composer require php-amqplib/php-amqplib
Example 2: Behavior and Validation
Publish a persistent message to a durable queue; default guest credentials are suitable only for isolated local demonstrations.
<?php
require __DIR__.'/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
$connection=new AMQPStreamConnection('127.0.0.1',5672,'guest','guest');
$channel=$connection->channel();
$channel->queue_declare('jobs',false,true,false,false);
$message=new AMQPMessage(json_encode(['job'=>'sync','id'=>42],JSON_THROW_ON_ERROR),['delivery_mode'=>2]);
$channel->basic_publish($message,'','jobs');
$channel->close(); $connection->close();
Practical Example: Application Use
Validate payload size and include a stable trace identifier before publication.
<?php
$body=json_encode(['type'=>'index.refresh','request_id'=>bin2hex(random_bytes(8))],JSON_THROW_ON_ERROR);
if (strlen($body)>65536) throw new LengthException('Job payload too large');
echo 'Payload bytes: ',strlen($body);
Important Behavior and Edge Cases
The second example highlights: Publish a persistent message to a durable queue; default guest credentials are suitable only for isolated local demonstrations. The practical example adds: Validate payload size and include a stable trace identifier before publication.
Comparison with Related Approaches
| Approach | What changes |
|---|---|
| Producer, consumer and scheduler | A producer publishes work, a consumer executes it, and the broker or scheduler controls delivery and retries. |
| Choosing safely | Acknowledge completed work and use idempotency to make retries safe. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Acknowledging a job before it finishes | Mark delivery successful only after durable processing succeeds. |
| Treating retries as harmless | Use idempotency keys and a bounded retry policy with dead-letter handling. |
| Skipping operational constraints | Use publisher confirms and durable queues when loss prevention matters. |
Key Takeaways
- AMQP publishers serialize a durable payload and route it via an exchange to a bound queue.
- Validate payload size and include a stable trace identifier before publication.
- Acknowledge completed work and use idempotency to make retries safe.