Skip to content

Instantly share code, notes, and snippets.

@rpkamp
Last active December 27, 2020 13:01
Show Gist options
  • Save rpkamp/f9c21110e441fb35c15c3a8d3d0361e1 to your computer and use it in GitHub Desktop.
Save rpkamp/f9c21110e441fb35c15c3a8d3d0361e1 to your computer and use it in GitHub Desktop.
Google Cloud Platform pub/sub PHP example
{
"require": {
"google/cloud-pubsub": "^0.12.0"
}
}
<?php
require 'vendor/autoload.php';
use Google\Cloud\PubSub\PubSubClient;
$pubSub = new PubSubClient([
'projectId' => 'my_project'
]);
$topic = $pubSub->topic('my_topic');
if (!$topic->exists()) {
$pubSub->createTopic('my_topic');
}
// Publish a message to the topic.
$topic->publish([
'data' => 'My new message.',
'attributes' => [
'location' => 'Detroit'
]
]);
<?php
require 'vendor/autoload.php';
use Google\Cloud\PubSub\PubSubClient;
$pubSub = new PubSubClient([
'projectId' => 'my_project'
]);
$subscription = $pubSub->subscription('my_subscription');
if (!$subscription->exists()) {
$pubSub->subscribe('my_subscription', 'my_topic');
}
// TODO: listen for SIGTERM and SIGKILL and stop the loop
while (true) {
$messages = $subscription->pull();
foreach ($messages as $message) {
echo '>> New message, received at ', date('Y-m-d H:i:s'), "\n";
echo 'Data: ', $message->data() , "\n";
echo 'Location: ', $message->attribute('location'), "\n\n";
$subscription->acknowledge($message);
}
}
@rpkamp
Copy link
Author

rpkamp commented Dec 27, 2020

This setup is only meant for pull. For push, please follow the examples provided by google itself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment