RabbitMQ is a message bus that allows you to send and receive messages via the Pub/Sub pattern . It is a great way to decouple different responsibilities of your system.
In this post I will show you how to write a simple consumer ( subscriber ) in PHP.
Setup the required composer packages
First a composer file:
I will be using symfony/console to create an easy to use console command, symfony/yaml to read out some config, and php-ampqlib for the consumer.
Install the required packages:
Setup config for RabbitMQ
The next step would be some config, i will be using the symfony structure for this, i will have a app/config/parameters.yml file with the content:
Now your project has composer.json, composer.lock, app directory and a vendor directory.
Create a console entry point
Create the following file at bin/console
Don’t forget to chmod +x bin/console
When you run it, it should give default symfony console output:
Create a consumer command
The consumer will do only 1 thing, that is echo anything that it comes from RabbitMQ
Created an Echo Service that is callable and recieves an AMQPMessage, AMQPMessage will hold all the information from the RabbitMQ Message.
Create an Echo Service
And create a command that chains console and the service together
Create the Command
As you can see the method $channel->basic_consume expects the echo service as one of the parameters, and it expects it to be a callable. Hence the __invoke on the EchoService
Add your PHP Consumer Command to bin/console
When you run the console command, it should show an extra command:
When you try to run your command ./bin/console arnovr:consumer-hello-world, it will throw an error
Logically, we don’t have RabbitMQ yet !
Setup the docker environment
A docker compose file that will setup our consumer and RabbitMQ
And define our service with PHP7.1
Lets start our service!
RabbitMQ needs some time to get up, there for i will up each service separately.
See if it works
Browse to: http://localhost:15672/#/
You should see 1 consumer and 1 queue:
Click on “queues” and “publish message”
You should see it posted on your consumer:
Developers say that PHP is bad in long lived processes.
They are partially correct, it is obvious that the language is not designed to be long lived.
However when you look out for memory problems, it is not a problem, and PHP will run for months without problems.