Building Simple PHP Applications Communicating via RabbitMQ

  ·   3 min read

Introduction

In modern application development, building microservices that communicate with one another efficiently is critical. Messaging systems like RabbitMQ have become a standard approach, facilitating asynchronous communication. In this article, we will examine how to create a simple PHP application where two separate PHP scripts communicate with each other using RabbitMQ.

What is RabbitMQ?

RabbitMQ is an open-source message broker that implements the Advanced Message Queuing Protocol (AMQP). It enables apps to communicate and share information despite being loosely coupled. It supports multiple messaging protocols and delivers messages with great reliability, making it an excellent choice for microservice architectures.

Setting Up Your Environment

Before diving into the code, let’s set up RabbitMQ and PHP. The easiest way to run RabbitMQ is through Docker. If you don’t have Docker installed, you can refer to the official documentation.

Step 1: Run RabbitMQ with Docker

To start a RabbitMQ server, execute the following command in your terminal:

docker run -d --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3-management
  • 5672 is the default port for RabbitMQ clients.
  • 15672 is the management plugin’s port where you can access the RabbitMQ dashboard.

You can access the management interface by navigating to http://localhost:15672/. The default username and password are both guest.

Step 2: Install PHP and Required Extensions

Make sure PHP and Composer are installed in your environment. You will also need the following extensions enabled:

  • php-amqplib: This library provides a clean and easy way to work with RabbitMQ in PHP. Install it using Composer with the command:
composer require php-amqplib/php-amqplib

Building the PHP Applications

Step 3: Create the Producer Application

The producer sends messages to a queue. Create a file named producer.php with the following code:

<?php
require 'vendor/autoload.php';

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();

$channel->queue_declare('task_queue', false, true, false, false, false, []);

$data = json_encode(['task' => 'Hello from PHP'], JSON_PRETTY_PRINT);
$msg = new AMQPMessage($data, ['delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT]);

$channel->basic_publish($msg, '', 'task_queue');

echo " [x] Sent 'Hello from PHP'\n";

$channel->close();
$connection->close();
?>

Step 4: Create the Consumer Application

The consumer listens for messages from the queue. Create another file named consumer.php with the following code:

<?php
require 'vendor/autoload.php';

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();

$channel->queue_declare('task_queue', false, true, false, false, false, []);

echo " [*] Waiting for messages. To exit press CTRL+C\n";

$callback = function ($msg) {
    echo " [x] Received ", $msg->body, "\n";
    sleep(substr_count($msg->body, '.'));
    echo " [x] Done\n";
};

$channel->basic_qos(null, 1, null);
$channel->basic_consume('task_queue', '', false, false, false, false, $callback);

while ($channel->is_consuming()) {
    $channel->wait();
}

$channel->close();
$connection->close();
?>

Step 5: Running the Applications

To see the producer and consumer in action, follow these steps:

  1. Open a terminal and run the consumer:

    php consumer.php
    
  2. In another terminal, run the producer several times:

    php producer.php
    

You will see messages being sent from the producer and received by the consumer. Each consumer message simulates processing time according to its content.

Conclusion

In this article, we explored how to create simple PHP applications that communicate asynchronously through RabbitMQ. RabbitMQ plays a crucial role in ensuring reliable message delivery between decoupled applications. This setup can be extended to handle complex workflows fitting for microservices architecture.

For further reading, consider checking out these resources:

By implementing message queues, you can build more responsive, resilient, and scalable applications, paving the way for efficient system architectures.