PHP code example of twipi-group / googlecloud-pubsub-php-adapter

1. Go to this page and download the library: Download twipi-group/googlecloud-pubsub-php-adapter library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

twipi-group / googlecloud-pubsub-php-adapter example snippets


use Google\Cloud\PubSub\PubSubClient;
use TwipiGroup\GoogleCloudPubSubPhpAdapter\GcPubSub;

$client = new PubSubClient([
    'projectId' => 'your-googlecloud-project-id',
]);

$pubsub = new GcPubSub($client);

$pubsub->publish('mychannel', 'test first');
$pubsub->publish('mychannel', json_encode(['test' => 'another']));
$pubsub->publish('mytopic', [
    'test' => [0, 1, 2]
]);

use Google\Cloud\PubSub\PubSubClient;
use TwipiGroup\GoogleCloudPubSubPhpAdapter\GcPubSub;

$client = new PubSubClient([
    'projectId' => 'your-googlecloud-project-id',
]);

$pubsub = new GcPubSub($client);

// case blocking call
$pubsub->subscribe('mychannel', function ($message) {
    var_dump($message);
});
// OR
$pubsub->subscribe('mysubscriber', function ($message) {
    var_dump($message);
}, 'mytopic');

// case non blocking call
$messages = $pubsub->consume('mychannel');
// OR
$messages = $pubsub->consume('mysubscriber', 'mytopic');

foreach ($messages as $message) {
    var_dump($message);
}

// set max messages number consuming by pull
$pubsub->setMaxMessages(2); // 100 by default

// set if return immediately after pull
$pubsub->setReturnImmediately(true); // false by default

// set delay in seconds to wait between each pull
// note: if ReturnImmediately is false, this option has no effect.
$pubsub->setDelay(2); // 10 by default

// set a suffix for subscriptions
$pubsub->setTopicSuffix('mysubsriber_'); // empty by default

// set debug mode to display pull messages directly to output
$pubsub->setDebug(true); // false by default

// set if auto create topic when not existing
$pubsub->setAutoCreateTopic(false); // true by default

// set if auto create subscription when not existing
$pubsub->setAutoCreateSubscription(false); // true by default

// set if auto create topic from subscription name when consume messages with empty topic name
$pubsub->setAutoCreateTopicFromSubscription(false); // true by default