PHPackages                             mouf/oo-amqp-client - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Queues &amp; Workers](/categories/queues)
4. /
5. mouf/oo-amqp-client

ActiveLibrary[Queues &amp; Workers](/categories/queues)

mouf/oo-amqp-client
===================

An object oriented wrapper on top of php-amqplib helping work with RabbitMQ in a more object oriented way.

v1.1.2(7y ago)1171.1k↓40%7[1 issues](https://github.com/thecodingmachine/oo-amqp-client/issues)MITPHPPHP &gt;=7.0

Since Dec 1Pushed 7y ago6 watchersCompare

[ Source](https://github.com/thecodingmachine/oo-amqp-client)[ Packagist](https://packagist.org/packages/mouf/oo-amqp-client)[ Docs](http://mouf-php.com/packages/mouf/oo-amqp-client)[ RSS](/packages/mouf-oo-amqp-client/feed)WikiDiscussions 1.1 Synced 1mo ago

READMEChangelog (4)Dependencies (7)Versions (6)Used By (0)

[![Latest Stable Version](https://camo.githubusercontent.com/7b6b7abd6803653f49882052bf30d0d1d4e949526d18fc00f7dacde634aa72f3/68747470733a2f2f706f7365722e707567782e6f72672f6d6f75662f6f6f2d616d71702d636c69656e742f762f737461626c65)](https://packagist.org/packages/mouf/oo-amqp-client)[![Total Downloads](https://camo.githubusercontent.com/d355569f59e357ff0004002c6275d9bb1ef429f32f688ae005d3847438a1f69c/68747470733a2f2f706f7365722e707567782e6f72672f6d6f75662f6f6f2d616d71702d636c69656e742f646f776e6c6f616473)](https://packagist.org/packages/mouf/oo-amqp-client)[![Latest Unstable Version](https://camo.githubusercontent.com/f39af78aaa1f645795d2c4987c8006a909da72019975f79e723ac07c1af715b5/68747470733a2f2f706f7365722e707567782e6f72672f6d6f75662f6f6f2d616d71702d636c69656e742f762f756e737461626c65)](https://packagist.org/packages/mouf/oo-amqp-client)[![License](https://camo.githubusercontent.com/58e96857deeee115b5e90493977739a0421ac38bbd8dcf617c9b26909d885e77/68747470733a2f2f706f7365722e707567782e6f72672f6d6f75662f6f6f2d616d71702d636c69656e742f6c6963656e7365)](https://packagist.org/packages/mouf/oo-amqp-client)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/5f21055c6f8daeceeaa5f0780569ea47a87f79d0baddb47b8f5d56c9840f90f4/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f746865636f64696e676d616368696e652f6f6f2d616d71702d636c69656e742f6261646765732f7175616c6974792d73636f72652e706e673f623d312e31)](https://scrutinizer-ci.com/g/thecodingmachine/oo-amqp-client/?branch=1.1)[![Build Status](https://camo.githubusercontent.com/1b31331ae1d3c2cb38c12999aedc09692f836431808d55c78dd63cc969c21c48/68747470733a2f2f7472617669732d63692e6f72672f746865636f64696e676d616368696e652f6f6f2d616d71702d636c69656e742e7376673f6272616e63683d312e31)](https://travis-ci.org/thecodingmachine/oo-amqp-client)[![Coverage Status](https://camo.githubusercontent.com/5a9d579a3df074bb8301ad4249e4c003777a0f24988233f63960eee7a655518e/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f746865636f64696e676d616368696e652f6f6f2d616d71702d636c69656e742f62616467652e7376673f6272616e63683d312e3126736572766963653d676974687562)](https://coveralls.io/github/thecodingmachine/oo-amqp-client?branch=1.1)

About Object Oriented AMQP Client
=================================

[](#about-object-oriented-amqp-client)

This package contains an object oriented wrapper on top of php-amqplib helping work with RabbitMQ in a more object oriented way.

Using this package, *exchanges*, *bindings* and *queues* are represented as objects. This is useful, especially if you want to inject those objects in your dependency injection container.

Installation
============

[](#installation)

```
composer require mouf/oo-amqp-client

```

Usage
=====

[](#usage)

Before using this library, you should be accustomed to the AMQP concepts. If you are not, we strongly advise you to start reading the ["AMQP 0-9-1 Model Explained" document from the RabbitMQ documentation](https://www.rabbitmq.com/tutorials/amqp-concepts.html).

Done? Let's get started.

Creating a client
-----------------

[](#creating-a-client)

The first thing you want to create is a `Client` object. A `Client` represents a connection to RabbitMQ (for those of you used to php-amqplib, it is both a connection AND a channel).

```
use Mouf\AmqpClient\Client;

$client = new Client(
    $rabbitmq_host,
    $rabbitmq_port,
    $rabbitmq_user,
    $rabbitmq_password,
    $rabbitmq_vhost = '/',
    $rabbitmq_insist = false,
    $rabbitmq_login_method = 'AMQPLAIN',
    $rabbitmq_login_response = null,
    $rabbitmq_locale = 'en_US',
    $rabbitmq_connection_timeout = 3.0,
    $rabbitmq_read_write_timeout = 3.0,
    $rabbitmq_context = null,
    $rabbitmq_keepalive = false,
    $rabbitmq_heartbeat = 0
);
```

Note: the `Client` class exposes a number of useful configuration methods (you do not need to use those if you don't know what they do):

```
public function setPrefetchSize($prefetchSize);
public function setPrefetchCount($prefetchCount);
public function setAGlobal($aGlobal);
```

Creating an exchange
--------------------

[](#creating-an-exchange)

In AMQP, *exchanges* are the objects that receive messages and are in charge of forwarding those messages to queues. You must therefore define an `Exchange` objects to send messages.

```
use Mouf\AmqpClient\Objects\Exchange;

$exchange = new Exchange($client, 'exchange_name', 'fanout');
```

When creating an exchange, you pass to the constructor the `Client` object, the exchange name, and the exchange type.

Note: the exchange will *self-register* in the client.

You can apply advanced configuration using configuration methods:

```
public function setPassive($passive);
public function setDurable($durable);
public function setAutoDelete($autoDelete);
public function setInternal($internal);
public function setNowait($nowait);
public function setArguments($arguments);
public function setTicket($ticket);
```

Creating a queue and a binding
------------------------------

[](#creating-a-queue-and-a-binding)

Messages arriving to an exchange are forwarded to a *queue* through a *binding*.

We will now create a queue to store our messages.

```
use Mouf\AmqpClient\Objects\Queue;

$queue = new Queue($client, 'queue_name', [
    new Consumer(function(AMQPMessage $msg) {
        // Do some stuff with the received message
    })
]);
```

When creating a client, you pass to the constructor the `Client` object, the client name, and an array of `Consumer` objects (actually an array of objects implementing the `ConsumerInterface`).

A `Consumer` object is an object that contains code that will be called each time a message is received.

Note: the queue will *self-register* in the client.

You can apply advanced configuration to your queue using those configuration methods:

```
public function setPassive($passive);
public function setDurable($durable);
public function setExclusive($exclusive);
public function setAutoDelete($autoDelete);
public function setNoWait($noWait);
public function setArguments($arguments);
public function setTicket($ticket);
public function setDeadLetterExchange(Exchange $exchange);
public function setConfirm($confirm);
public function setConsumerCancelNotify(Queue $consumerCancelNotify);
public function setAlternateExchange(Queue $alternateExchange);
public function setTtl($ttl);
public function setMaxLength($maxLength);
public function setMaxPriority($maxPriority);
```

You will certainly want to use the `setDurable` method if you want your queue to store messages in case of outage of the receiver.

At this point, we have an *exchange*, we have a *queue*, but both are not linked together. We need to **bind** those, using a `Binding` object.

```
use Mouf\AmqpClient\Objects\Binding;

$binding = new Binding($exchange, $queue);
$client->register($binding);
```

A `Binding` links an exchange to a queue.

**Important**: unlike the `Exchange` and the `Queue`, a `Binding` does not self-register in the client. You have to declare it in the client yourself, using the `Client::register` method.

Done? Let's send and receive messages!

Sending a message
-----------------

[](#sending-a-message)

In order to send a message, you simply use the `Exchange::publish` method:

```
$exchange->publish(new Message('your message body'), 'message_key');
// ... and that's it!
```

You may still want to configure a bit more the sending of your message. The `Exchange::publish` method accepts a number of optional arguments:

```
public function publish(Message $message,
                        string $routingKey,
                        bool $mandatory = false,
                        bool $immediate = false,
                        $ticket = null);
```

Also, the `Message` class can be tweaked with one of those methods:

```
public function setContentType(string $content_type);
public function setContentEncoding(string $content_encoding);
public function setApplicationHeaders(array $application_headers);
public function setDeliveryMode(int $delivery_mode);
public function setPriority(int $priority);
public function setCorrelationId(string $correlation_id);
public function setReplyTo(string $reply_to);
public function setExpiration(string $expiration);
public function setMessageId(string $message_id);
public function setTimestamp(\DateTimeInterface $timestamp);
public function setType(string $type);
public function setUserId(string $user_id);
public function setAppId(string $app_id);
public function setClusterId(string $cluster_id);
```

Receiving messages
------------------

[](#receiving-messages)

As we already saw, the first step to receiving message is creating a queue and adding `Consumer` objects to that queue.

We still need to tell PHP to start listening, otherwise, the callbacks in the `Consumer` will never be called.

This can be done using the `ConsumerService` class.

```
$consumerService = new ConsumerService($client, [
    $queue
]);

$consumerService->run();
```

The `ConsumerService` constructor takes the client in parameter, and the array of queues that must be listened to.

The `ConsumerService::run` method will start listening on arriving messages, in an infinite loop.

Notice that you can use `$consumerService->run(true);` if you want to listen to one message only and return afterward.

Acknowledgements and error handling
-----------------------------------

[](#acknowledgements-and-error-handling)

When you receive a message, an acknowledgement will not be sent before the `Consumer` has finished consuming the message.

If an exception is triggered in the `Consumer`, a `nack` will be sent instead to RabbitMQ.

Note: if your consumer callback throws an exception implementing the `RetryableExceptionInterface` interface, the `nack` message will be sent with the "requeue" flag. The message will be requeued.

Note: if your consumer callback throws an exception implementing the `FatalExceptionInterface` interface, the exception will be propagated by the consumer (hence leading to the crash of the consumer script). Otherwise, consumer will continue processing messages.

Exceptions are logged by default using the error\_log function. You can override this behaviour by passing a PSR-3 compliant logger to the `AbstractConsumer` constructor.

Writing your consumer as a class
--------------------------------

[](#writing-your-consumer-as-a-class)

So far, to create a consumer, we used the `Consumer` class that takes a callback as first constructor parameter.

As an alternative, you can extend the `AbstractConsumer` class and implement the `onMessageReceived` method:

```
class MyConsumer extends AbstractConsumer
{
    public function onMessageReceived($msg)
    {
        // Do some stuff.
    }
}
```

Sending a message to a given queue
----------------------------------

[](#sending-a-message-to-a-given-queue)

If you want to target a special queue and send a message to it directly, you have 2 options.

**Option 1**: create a `DefaultExchange` object and pass the queue name as the key of the message.

```
use Mouf\AmqpClient\Objects\DefaultExchange;

$exchange = new DefaultExchange($client);
// Simply pass the queue name as the second parameter of "publish".
// Note: you do not need to bind the queue to the exchange. RabbitMQ does this automatically.
$exchange->publish(new Message('your message body'), 'name_of_the_target_queue');
// ... and that's it!
```

**Option 2**: use the `publish` method of the `Queue` object:

```
use Mouf\AmqpClient\Objects\Queue;

$queue = new Queue($client, 'queue_name', [
    new Consumer(function(AMQPMessage $msg) {
        // Do some stuff with the received message
    })
]);

// Shazam! We are directly sending a message to the queue. No exchange needed!
$queue->publish(new Message('your message body'));
```

Note: these are RabbitMQ specific features and might not work with other AMQP buses.

Symfony console integration
---------------------------

[](#symfony-console-integration)

This package comes with 2 Symfony commands that you can use to send and receive messages.

- `Mouf\AmqpClient\Commands\PublishCommand` (`amqp:publish`) allows you to send an arbitrary message on an exchange (read from a file or from STDIN)
- `Mouf\AmqpClient\Commands\ConsumeCommand` (`amqp:consume`) listen to all configured queues

Running the unit tests
======================

[](#running-the-unit-tests)

This package uses PHPUnit for unit tests.

To run the tests:

```
vendor/bin/phpunit

```

Obviously, you need a running RabbitMQ server to test this package. If you use Docker, you can start one using:

```
docker run -p 5672:5672 -p 15672:15672 rabbitmq:management
```

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance0

Infrequent updates — may be unmaintained

Popularity34

Limited adoption so far

Community18

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor1

Top contributor holds 70% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~139 days

Recently: every ~163 days

Total

6

Last Release

2757d ago

PHP version history (2 changes)v1.0.0PHP &gt;=5.6

v1.1.0PHP &gt;=7.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/1104771?v=4)[mouf](/maintainers/mouf)[@Mouf](https://github.com/Mouf)

---

Top Contributors

[![moufmouf](https://avatars.githubusercontent.com/u/1290952?v=4)](https://github.com/moufmouf "moufmouf (42 commits)")[![Ngob](https://avatars.githubusercontent.com/u/2749238?v=4)](https://github.com/Ngob "Ngob (7 commits)")[![gregoireMIAGE](https://avatars.githubusercontent.com/u/11410668?v=4)](https://github.com/gregoireMIAGE "gregoireMIAGE (5 commits)")[![jeremiepose](https://avatars.githubusercontent.com/u/1080425?v=4)](https://github.com/jeremiepose "jeremiepose (4 commits)")[![gparant](https://avatars.githubusercontent.com/u/23724509?v=4)](https://github.com/gparant "gparant (2 commits)")

---

Tags

hydratorTDBM

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mouf-oo-amqp-client/health.svg)

```
[![Health](https://phpackages.com/badges/mouf-oo-amqp-client/health.svg)](https://phpackages.com/packages/mouf-oo-amqp-client)
```

###  Alternatives

[symfony/messenger

Helps applications send and receive messages to/from other applications or via message queues

1.1k120.7M958](/packages/symfony-messenger)[php-amqplib/rabbitmq-bundle

Integrates php-amqplib with Symfony &amp; RabbitMq. Formerly emag-tech-labs/rabbitmq-bundle, oldsound/rabbitmq-bundle.

1.3k20.1M65](/packages/php-amqplib-rabbitmq-bundle)[hyperf/amqp

A amqplib for hyperf.

241.2M56](/packages/hyperf-amqp)[convenia/pigeon

3233.0k](/packages/convenia-pigeon)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
