Writing and Responding to Pub/Sub Messages


This document describes how to use the Google Cloud Client Library to send and receive Cloud Pub/Sub messages in an app running in the flexible environment.


  • Follow the instructions in "Hello, World!" for PHP on App Engine to set up your environment and project, and to understand how App Engine PHP apps are structured.

Cloning the sample app


git clone https://github.com/GoogleCloudPlatform/getting-started-php.git
cd getting-started-php/pubsub

Creating a topic and subscription


gcloud pubsub topics create YOUR_TOPIC_NAME
gcloud pubsub subscriptions create YOUR_SUBSCRIPTION_NAME \
    --topic YOUR_TOPIC_NAME

Setting environment variables

Edit your index.php file to set the environment variables for your topic and subscription:

$app['topic'] = 'php-example-topic';
$app['subscription'] = 'php-example-subscription';

Code review

The sample app uses the Google Cloud Client Libraries.


runtime: php
env: flex

The sample app maintains a global list to store messages received by this instance:

$messages = [];

The pull method retrieves messages from the topic you created and adds them to the messages list:

// get PULL pubsub messages
$pubsub = new PubSubClient([
    'projectId' => $projectId,
$subscription = $pubsub->subscription($subscriptionName);
$pullMessages = [];
foreach ($subscription->pull(['returnImmediately' => true]) as $pullMessage) {
    $pullMessages[] = $pullMessage;
    $messages[] = $pullMessage->data();
// acknowledge PULL messages
if ($pullMessages) {

The publish method publishes new messages to the topic:

if ($message = $app['request']->get('message')) {
    // Publish the pubsub message to the topic
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    $topic = $pubsub->topic($topicName);
    $response = $topic->publish(['data' => $message]);
    return new Response('', 204);

Running the sample locally


Install dependencies using Composer:

composer install

Then set environment variables before starting your application:

Simulating push notifications


You can use curl or httpie to send an HTTP POST request:





Running on App Engine


gcloud app deploy

You can now access the application at https://[YOUR_PROJECT_ID].appspot.com. You can use the form to submit messages, but there's no guarantee of which instance of your application will receive the notification. You can send multiple messages and refresh the page to see the received message.

¿Te ha resultado útil esta página? Enviar comentarios:

Enviar comentarios sobre...

App Engine flexible environment for PHP docs