The `php-amqplib/php-amqplib` library is a pure PHP client for the Advanced Message Queuing Protocol (AMQP) 0-9-1. It provides a robust and flexible way for PHP applications to communicate with AMQP message brokers like RabbitMQ. AMQP is an open standard application layer protocol for message-oriented middleware. It allows for the asynchronous, secure, and reliable exchange of messages between different applications, services, or components.\n\n Why use php-amqplib?\nAMQP message brokers are widely used in modern distributed systems for various purposes:\n* Asynchronous Processing: Offloading long-running tasks (e.g., image processing, email sending, report generation) from the main request/response cycle.\n* Decoupling Applications: Allowing different parts of a system (e.g., microservices) to communicate without direct dependencies, improving scalability and resilience.\n* Load Balancing: Distributing tasks among multiple worker processes.\n* Reliable Messaging: Ensuring messages are delivered, even if consumers fail.\n\n`php-amqplib` enables PHP applications to act as both producers (sending messages) and consumers (receiving messages) in an AMQP ecosystem.\n\n Core AMQP Concepts relevant to php-amqplib:\n1. Connection: Establishes a TCP/IP connection to the AMQP broker (e.g., RabbitMQ server). This is the initial handshake.\n2. Channel: A lightweight logical connection multiplexed over a single TCP connection. Most AMQP operations (declaring queues, publishing messages) are done over a channel. You can have multiple channels over one connection.\n3. Exchange: Messages are not published directly to queues; instead, a producer sends them to an exchange. The exchange then routes the messages to one or more queues based on rules defined by its type and routing keys.\n * Direct Exchange: Routes messages to queues whose binding key exactly matches the message's routing key.\n * Fanout Exchange: Routes messages to all queues bound to it, ignoring the routing key.\n * Topic Exchange: Routes messages to queues based on pattern matching with routing keys (e.g., `logs.*`, `*.error`).\n * Headers Exchange: Routes messages based on message header attributes.\n4. Queue: A named buffer that stores messages until they are consumed. Queues can be durable (persisting messages across broker restarts), exclusive (only accessible by one connection), or auto-delete (deleted when the last consumer disconnects).\n5. Binding: A relationship between an exchange and a queue. It tells the exchange to route messages (based on a binding key) to a specific queue.\n6. Producer: An application that creates and sends messages to an exchange.\n7. Consumer: An application that receives messages from a queue and processes them.\n\n Installation:\n`php-amqplib` is typically installed via Composer:\n```bash\ncomposer require php-amqplib/php-amqplib\n```\n\n Basic Workflow (Producer):\n1. Connect to the AMQP broker.\n2. Open a channel.\n3. Declare an exchange (if it doesn't exist or you want to ensure its configuration).\n4. Publish messages to the exchange, specifying a routing key.\n\n Basic Workflow (Consumer):\n1. Connect to the AMQP broker.\n2. Open a channel.\n3. Declare a queue (if it doesn't exist or you want to ensure its configuration).\n4. Declare an exchange (if messages are routed via an exchange).\n5. Bind the queue to the exchange (if using an exchange).\n6. Set up a callback function to process incoming messages.\n7. Start consuming messages from the queue, typically in a loop.
Example Code
<?php\n\nrequire_once __DIR__ . '/vendor/autoload.php';\n\nuse PhpAmqpLib\Connection\AMQPStreamConnection;\nuse PhpAmqpLib\Message\AMQPMessage;\n\n// --- Producer Example: Sending a Message --- \n\n// 1. Establish a connection to the AMQP broker\n// Replace 'localhost' with your RabbitMQ host if it's not local.\n// Default port for AMQP is 5672.\n// Default credentials for RabbitMQ are 'guest'/'guest'.\ntry {\n $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');\n $channel = $connection->channel();\n\n // 2. Declare an exchange\n // Arguments:\n // - exchange name: 'my_exchange'\n // - exchange type: 'fanout' (sends to all bound queues)\n // - passive: false (create if it doesn't exist)\n // - durable: true (exchange will survive broker restarts)\n // - auto_delete: false (exchange won't be deleted when no longer in use)\n // - internal: false (can be used by external publishers)\n $channel->exchange_declare('my_exchange', 'fanout', false, true, false);\n\n // 3. Declare a queue\n // Arguments:\n // - queue name: '' (empty string will generate a unique name)\n // - passive: false\n // - durable: false (queue will be deleted when broker restarts)\n // - exclusive: true (queue only available to this connection, deleted on disconnect)\n // - auto_delete: true (queue deleted when last consumer unsubscribes)\n list($queueName, ,) = $channel->queue_declare('', false, false, true, true);\n\n // 4. Bind the queue to the exchange\n // This tells the exchange to send messages to this queue.\n // For a 'fanout' exchange, the routing key is ignored, so we can pass an empty string.\n $channel->queue_bind($queueName, 'my_exchange');\n\n // 5. Create a message\n $data = "Hello World from PHP! " . date('Y-m-d H:i:s');\n $msg = new AMQPMessage($data,\n [\n 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT // Make message persistent\n ]\n );\n\n // 6. Publish the message to the exchange\n // Arguments:\n // - message object\n // - exchange name\n // - routing key (empty for fanout)\n $channel->basic_publish($msg, 'my_exchange', '');\n\n echo " [x] Sent '{$data}' to exchange 'my_exchange' (bound to queue '{$queueName}')\\n";\n\n} catch (Exception $e) {\n echo " [!] Error: " . $e->getMessage() . "\\n";\n} finally {\n // 7. Close the channel and connection\n if (isset($channel)) {\n $channel->close();\n }\n if (isset($connection)) {\n $connection->close();\n }\n}\n\n// --- To run this example: ---\n// 1. Make sure you have RabbitMQ running.\n// 2. Install php-amqplib via Composer: `composer require php-amqplib/php-amqplib`\n// 3. Save the code as a .php file (e.g., producer.php).\n// 4. Run from your terminal: `php producer.php`\n\n// --- For a Consumer Example (conceptual): ---\n// A consumer would connect in a similar way, declare its queue (or use the one created by the producer if durable),\n// and then use `$channel->basic_consume($queueName, '', false, true, false, false, $callback);`\n// inside a loop to listen for messages. The `$callback` function would process each message.\n// Example of a consumer callback (would be in a separate consumer script):\n/*\nfunction processMessage(AMQPMessage $msg)\n{\n echo " [x] Received " . $msg->body . "\\n";\n $msg->ack(); // Acknowledge message processing\n}\n\n// In consumer script:\n// $channel->basic_consume($queueName, '', false, false, false, false, 'processMessage');\n// while ($channel->is_consuming()) {\n// $channel->wait();\n// }\n*/\n








php-amqplib/php-amqplib