This topic describes how to use the SDK for PHP to create a queue, send a message, receive and delete the message, and delete the queue.

Step 1: Prepare the environment

  1. Download the latest version of the SDK for PHP, decompress the package, and then go to the aliyun-mns-php-sdk-master/Samples/Queue subdirectory.
  2. Open the CreateQueueAndSendMessage.php file, and specify the AccessKey ID, AccessKey secret, and endpoint at the end of the file.
    • AccessKey ID and AccessKey secret
      • The AccessKey pair that is used to call API operations in Alibaba Cloud.
      • If you are using an Alibaba Cloud account, go to the AccessKey Management page of the Alibaba Cloud Management Console to create and view your AccessKey pair.
      • If you are a Resource Access Management (RAM) user, log on to RAM console to view your AccessKey pair.
    • Endpoint
      • The endpoint that is used to access MNS. To view the endpoint of Message Service (MNS), log on to the MNS console, and click Get Endpoint in the upper-right corner.
      • The endpoint of MNS varies based on different regions.
  3. Use the following code that is included in the CreateQueueAndSendMessage.php file to configure the SDK:
    // Declare required PHP classes.
    use AliyunMNS\Client;
    use AliyunMNS\Requests\SendMessageRequest;
    use AliyunMNS\Requests\CreateQueueRequest;
    use AliyunMNS\Exception\MnsException;

Step 2: Create a queue

If no queue is available, you must create a queue. The default name of the new queue is CreateQueueAndSendMessageExample. You can also specify another queue name.

// 1. Initialize a client.
$this->client = new Client($this->endPoint, $this->accessId, $this->accessKey);

// 2. Generate a request to create a queue. You can specify the parameters of the queue.
// For more information about the parameters of the queue, see Queue.
$request = new CreateQueueRequest($queueName);
try
{
        $res = $this->client->createQueue($request);
        // 3. The queue is created.
        echo "QueueCreated! \n";
}
catch (MnsException $e)
{
        // 4. The queue may fail to be created if a network error occurs or the queue name already exists. You can call the CatchException operation to identify and resolve the failure.
         echo "CreateQueueFailed: " . $e;
         return;
}            

Step 3: Send a message

After the queue is created, send a message to the queue.

// 1. Retrieve the queue.
// By default, the SDK for PHP performs Base64 encoding for sent messages and performs Base64 decoding for received messages.
// If you do not want the SDK to perform the preceding operations, you can set the Base64 parameter to FALSE when you call the getQueueRef() method: $queue = $this->client->getQueueRef($queueName, FALSE).
$queue = $this->client->getQueueRef($queueName);

$messageBody = "test";
// 2. Generate a request to send a message.
// You can specify the DelaySeconds and Priority parameters of the message.
// For more information about the parameters of the message, see QueueMessage.
$bodyMD5 = md5(base64_encode($messageBody));
$request = new SendMessageRequest($messageBody);
try
{
        $res = $queue->sendMessage($request)
        // 3. The message is sent.
        echo "MessageSent! \n";
}
catch (MnsException $e)
{
        // 4. The message may fail to be sent if a network error occurs or the message is oversized. You can query the cause and solve the problem.
        echo "SendMessage Failed: " . $e;
        return;
}            

Step 4: Receive and delete the message

If the message is sent, you can receive the message from the queue.

NextVisibleTime is an important parameter of the message in MNS. For more information, see QueueMessage.

$receiptHandle = NULL;
try
{
        // 1. Call the receiveMessage() function.
        // We recommend that you set the WaitSeconds parameter to 30 when you call the receiveMessage() function.
        // If you set the WaitSeconds parameter to a non-zero value, the request of receiving messages is an HTTP long polling request. A response is returned only if the message is sent to the queue or the request times out. The maximum value of the WaitSeconds parameter is 30.
        $res = $queue->receiveMessage(30);
        echo "ReceiveMessage Succeed! \n";
        if (strtoupper($bodyMD5) == $res->getMessageBodyMD5())
        {
             echo "You got the message sent by yourself! \n";
        }
        // 2. Retrieve the value of the ReceiptHandle parameter. The receipt handle of the message has a validity period and can be used to modify or delete the message. For more information, see QueueMessage.
        $receiptHandle = $res->getReceiptHandle();
}
catch (MnsException $e)
{
        // 3. The message may fail to be received if an error occurs. You can query the cause and solve the problem.
        echo "ReceiveMessage Failed: " . $e;
        return;
}

// Specify your own logic for processing messages based on your business requirements.
// The VisibilityTimeout parameter specifies the period when a message remains in the Inactive state in the queue after the message is received by a client. After the specified period, the message enters the Active state again and can be received by other clients. This prevents message loss against unexpected exits.

// 4. After the message is consumed, you can delete the message from the queue.
try
{
        // 5. Call the deleteMessage() function.
        $res = $queue->deleteMessage($receiptHandle);
        echo "DeleteMessage Succeed! \n";
}
catch (MnsException $e)
{
        // 6. If an error occurs, you can call the CatchException operation to identify and resolve the failure.
        // If the receipt handle expires, the MessageNotExist error is returned. This error indicates that you cannot use the receipt handle to find the corresponding message.
        // To ensure that you can consume the message before the receipt handle expires, you must set the VisibilityTimeout parameter to an appropriate value. You can call the changeMessageVisibility() function to modify the value of the VisibilityTimeout parameter.
        echo "DeleteMessage Failed: " . $e;
        return;
}            

Step 5: Delete the queue

You can use the following sample code to delete the queue:

try {
        $this->client->deleteQueue($queueName);
        echo "DeleteQueue Succeed! \n";
} catch (MnsException $e) {
        echo "DeleteQueue Failed: " . $e;
        return;
}