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

Step 1: Prepare the environment

  1. Download the latest version of the PHP SDK, decompress the package, and go to the php_sdk/Samples/Queue sub-directory.
  2. Open the CreateQueueAndSendMessage.php file, and configure the AccessKey ID, AccessKey secret, and endpoint in the last rows of the file.
    • AccessKey ID and AccessKey secret
      • The AccessKey pair that is used to access the Alibaba Cloud API.
      • If you are using an Alibaba Cloud account, go to the Security Management page of the Alibaba Cloud console to create and view AccessKey pairs.
      • If you are a RAM user, log on to Alibaba Cloud RAM console to view AccessKey pairs.
    • Endpoint
      • The endpoint that is used to access MNS. Log on to the MNS console, and click Get Endpoint in the upper-right corner to view endpoints.
      • The endpoint of MNS changes based on regions.
  3. Include the SDK into your code by using an include (or require) statement.
    //Include an SDK autoloader file.
    require_once(dirname(dirname(dirname(__FILE__))).'/mns-autoloader.php');
    
    //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 queues are available, you must create a queue. The default name of the new queue is CreateQueueAndSendMessageExample. You can also specify a 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 a queue.
// 2.1 For more information about the parameters of a queue, visit help.aliyun.com/document_detail/27476.html.
$request = new CreateQueueRequest($queueName);
try
{
        $res = $this->client->createQueue($request);
        // 2.2 The queue is created.
        echo "QueueCreated! \n";
}
catch (MnsException $e)
{
        // 2.3 The queue may fail to be created if a network error occurs or the queue already exists. You can query the cause and solve the problem.
        echo "CreateQueueFailed: " . $e . "\n";
        echo "MNSErrorCode: " . $e->getMnsErrorCode() . "\n";
        return;
}            

Step 3: Send a message

After creating a queue, you can send messages to the queue.

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

$messageBody = "test";
// 2. Generate a request to send a message.
// 2.1 You can specify the DelaySeconds and Priority parameters of a message.
// 2.2 For more information about the parameters of a message, visit help.aliyun.com/document_detail/27477.html.
$request = new SendMessageRequest($messageBody);
try
{
        $res = $queue->sendMessage($request);
        // 3. The message is sent.
        echo "MessageSent! \n";
}
catch (MnsException $e)
{
        // 4. A 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 . "\n";
        echo "MNSErrorCode: " . $e->getMnsErrorCode() . "\n";
        return;
}            

Step 4: Receive and delete the message

If messages exist in a queue, you can receive messages.

NextVisibleTime is an important parameter. For more information about this parameter, see Queue messages.

$receiptHandle = NULL;
try
{
        // 1. Call the receiveMessage() function.
        // 1.1 We recommend that you set the WaitSeconds parameter to 30 when calling the receiveMessage() function.
        // 1.2 If you set the WaitSeconds parameter to a non-zero value, a request of receiving messages is an HTTP long polling request. The server does not close the connection until it has a message to send. The maximum value of the WaitSeconds parameter is 30.
        $res = $queue->receiveMessage(30);
        echo "ReceiveMessage Succeed! \n";
        // 2. Retrieve the value of the ReceiptHandle parameter. The receipt handle of a message has a validity period and can be used to modify or delete the message. For more information about this parameter, visit help.aliyun.com/document_detail/27477.html.
        $receiptHandle = $res->getReceiptHandle();
}
catch (MnsException $e)
{
        // 3. A message may fail to be received if an error occurs. You can query the cause and solve the problem.
        echo "ReceiveMessage Failed: " . $e . "\n";
        echo "MNSErrorCode: " . $e->getMnsErrorCode() . "\n";
        return;
}

//Specify your own logic for processing messages based on your business needs.
//The VisibilityTimeout parameter specifies the period when a message remains inactive in the queue after being consumed by a client. After the specified period, the message becomes active again and can be consumed by other clients. The message will not be lost if the program crashes or is stuck.

// 4. After receiving the message, 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 query the cause and solve the problem.
        // 6.1 If a receipt handle expires, the following error code is returned: MessageNotExist. This error code indicates that you cannot use the receipt handle to find the corresponding message.
        // 6.2 To ensure that you can manage a message in a timely manner before the current 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 . "\n";
        echo "MNSErrorCode: " . $e->getMnsErrorCode() . "\n";
        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;
}