Example of using Yandex Message Queue on PHP

Using the AWS SDK for PHP, you can manage Message Queue message queues and send and receive messages.

Installation

Install the AWS SDK for PHP by following the instructions on the official site.

Before you start

  1. Create a service account.
  2. Assign a role to a editor service account.
  3. Create a static access key.

Set the environment variables:

$ export AWS_ACCESS_KEY_ID="<access key ID>"
$ export AWS_SECRET_ACCESS_KEY="<secret key>"

Example

In this example:

  1. A connection with Message Queue is established.
  2. A message queue is created with the name ymq_php_sdk_example.
  3. A message with the text Test message is sent to the queue.
  4. The message is read from the queue and displayed in the terminal.
  5. The message queue is deleted.
<?php

require 'vendor/autoload.php';

use Aws\SQS\SQSClient;
use Aws\Exception\AwsException;

$ymq = new Aws\SQS\SQSClient([
    'version' => 'latest',
    'region' => 'ru-central1',
    'endpoint' => 'https://message-queue.api.cloud.yandex.net',
]);

$result = $ymq->createQueue([
    'QueueName' => 'ymq_php_sdk_example',
]);

$queueUrl = $result["QueueUrl"];
print('Queue created, URL: ' . $queueUrl . PHP_EOL);

$result = $ymq->sendMessage([
    'QueueUrl' => $queueUrl,
    'MessageBody' => 'Test message',
]);

print("Message sent, ID: " . $result["MessageId"] . PHP_EOL);

$result = $ymq->receiveMessage([
    'QueueUrl' => $queueUrl,
    'WaitTimeSeconds' => 10,
]);

foreach ($result["Messages"] as $msg) {
    print('Message received:' . PHP_EOL);
    print('ID: ' . $msg['MessageId'] . PHP_EOL);
    print('Body: ' . $msg['Body'] . PHP_EOL);

    $ymq->deleteMessage([
        'QueueUrl' => $queueUrl,
        'ReceiptHandle' => $msg['ReceiptHandle'],
    ]);
}

$result = $ymq->deleteQueue([
    'QueueUrl' => $queueUrl,
]);

print('Queue deleted' . PHP_EOL);