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

Step 1: Prepare the environment

  1. Download the CreateTopicAndPublishMessage.php file.
  2. Open the CreateTopicAndSendMessage.php file and specify the following information:
    • AccessKey ID and AccessKey secret
      • The AccessKey pair that is used to call the API operations of 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 the RAM console to view your AccessKey pair.
    • Endpoint
      • The endpoint that is used to access Message Service (MNS). To view the endpoints of MNS, log on to the MNS console. For more information, see View the endpoints of a topic.
      • The endpoints of MNS vary based on regions.
  3. Modify the settings of the SDK

    Use the sample code at the beginning of the CreateTopicAndSendMessage.php file to specify the SDK.

    // Include an SDK autoload file. 
    require __DIR__ . '/vendor/autoload.php';
    
    // Declare required PHP classes. 
    use AliyunMNS\Client;
    use AliyunMNS\Model\SubscriptionAttributes;
    use AliyunMNS\Requests\PublishMessageRequest;
    use AliyunMNS\Requests\CreateTopicRequest;
    use AliyunMNS\Exception\MnsException;       

Step 2: Create a topic

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

// 1.Generate a request to create a topic. You can specify the parameters of a topic. 
$request = new CreateTopicRequest($topicName);
try
{
        $res = $this->client->createTopic($request);
        echo "TopicCreated! \n";
}
catch (MnsException $e)
{
        // 2.The topic may fail to be created if a network error occurs or the topic name already exists. You can call the CatchException or Catch TopicAlreadyExistException operation to identify and resolve the failure. 
        echo "CreateTopicFailed: " . $e . "\n";
        echo "MNSErrorCode: " . $e->getMnsErrorCode() . "\n";
        return;

Step 3: 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 4: Create a subscription

You can use the following sample code to create a subscription to the topic:

$regionId = "";
$accountId = "";
$queueName = "TestQueue";
$subscriptionName = "QueueEndpoint";

$attributes = new SubscriptionAttributes($subscriptionName, 'acs:mns:' . $regionId . ':' . $accountId . ':queues/' . $queueName);
try
{
        $topic->subscribe($attributes);
        // The subscription is successful. 
        echo "Subscribed! \n";
}
catch (MnsException $e)
{
        // The subscription may fail to be created if a network error occurs or the subscription name already exists. You can call the CatchException operation to identify and resolve the failure. 
        echo "SubscribeFailed: " . $e . "\n";
        echo "MNSErrorCode: " . $e->getMnsErrorCode() . "\n";
        return;
}         

Step 5: Publish a message

You can use the following sample code to publish a message to the topic:

$messageBody = "test";
// 1.Generate a PublishMessage request. If you need to send a message to an email address, you must specify the parameters of the message. For more information, see the testPublishMailMessage() function in the Tests/TopicTest.php file. 
$request = new PublishMessageRequest($messageBody);
try
{
        $res = $topic->publishMessage($request);
        // 2.The message is published. 
        echo "MessagePublished! \n";
}
catch (MnsException $e)
{
        // 3.The message may fail to be published if a network error occurs. You can call the CatchException operation to identify and resolve the failure. 
        echo "PublishMessage Failed: " . $e . "\n";
        echo "MNSErrorCode: " . $e->getMnsErrorCode() . "\n";
        return;
}            

Step 6: Receive and delete the message from the queue

After the message is pushed from a topic to a queue, you can receive and delete the message from the queue.

$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 to process messages based on your business requirements. 
// 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 is not lost if the program fails or is stuck. 

// 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 7: Delete the topic

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

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

Step 8: 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;
}