The previous blog post told you how to get started with RabbitMQ in PHP. This post covers the same image processing topic and dedicated to Symfony developers.

In this blogpost I am going to show how to use RabbitMQ to schedule some background tasks in Symfony full stack application. This article will be more about message queues than images. The future blog post will contain more practical stuff. It will tell us about LiipImagineBundle and how to prepare filtered images in background.

All examples are based on Enqueue PHP Messaging library.

I suppose you have already installed RabbitMQ broker and Symfony application.

The installation process contains three steps.

Step 1: Install Enqueue bundle and AMQP extension.

Step 2: Register the bundle in AppKernel.

Step 3: Configure the bundle .

Here’re these three steps:

Now let’s suppose you have already stored the uploaded image. We have to send the uploaded image path as a message to a background task. The task is able to read the image and perform actions on it (create thumbnail, apply filters, optimize size and so on).

To send such a message we have get a context service from a container. We use the context to create a queue, a message and producer objects. Having these objects in place we can finally send the message:

The code above may be placed at the end of a controller action.

The message is sent and we can proceed to the consumption part. First of all we have to create a processor class which implements the PsrProcessor interface. The process method must contain our image processing logic and must return self::ACK once it is done. The processor must be registered as a service in Symfony container.

Here are examples on how you can do it:

Finally we are ready to start consume messages. The bundle comes with some handy consume command and we are going to use it now:

$ ./bin/console enqueue:transport:consume process_image acme.process_image_processor -vvv

The command takes two arguments: a queue to consume from and a processor service id to pass messages to. Run as many instances of these commands as you want in order to gain better performance.

Conclusion

In this post we covered a message publishing and consumption in Symfony. We used RabbitMQ as a broker for that. We used a transport layer that is a verbose abstraction. There is a high level abstraction called client. It simplifies things a lot and supports extra features: message delaying, message bus, pub sub, broker setup and so on. We’ll cover it in dedicated blog post.

You can also visit our corporate blog to learn more about up-to-date IT trends and download some useful insights.