Cloud PubSub Client - Class MessageBuilder (1.43.2)

Reference documentation and code samples for the Cloud PubSub Client class MessageBuilder.

Builds a PubSub Message.

This class may be used to build an API-compliant message for publication.

This class is immutable and each build method returns a new instance with your changes applied.

Note that messages are invalid unless they include a data field or at least one attribute. Both may be provided, but omission of both will result in an error.

Example:

use Google\Cloud\PubSub\MessageBuilder;
use Google\Cloud\PubSub\PubSubClient;

$client = new PubSubClient();
$topic = $client->topic($topicId);

$builder = new MessageBuilder();
$builder = $builder->setData('hello friend!')
    ->addAttribute('from', 'Bob')
    ->addAttribute('to', 'Jane');

$topic->publish($builder->build());

Namespace

Google \ Cloud \ PubSub

Methods

__construct

Parameter
NameDescription
message array

The initial message data.

setData

Set the message data.

Do not base64-encode the value; If it must be encoded, the client will do it on your behalf.

Example:

$builder = $builder->setData('Hello friend!');
Parameter
NameDescription
data string

The message data field.

Returns
TypeDescription
Google\Cloud\PubSub\MessageBuilder

setAttributes

Set optional attributes for this message.

Example:

$builder = $builder->setAttributes([
    'from' => 'Bob'
]);
Parameter
NameDescription
attributes array

A set of key/value pairs, where both key and value are strings.

Returns
TypeDescription
Google\Cloud\PubSub\MessageBuilder

addAttribute

Add a single attribute to the message.

Example:

$builder = $builder->addAttribute('to', 'Jane');
Parameters
NameDescription
key string

The attribute key.

value string

The attribute value.

Returns
TypeDescription
Google\Cloud\PubSub\MessageBuilder

setOrderingKey

Set the message's ordering key.

Example:

$builder = $builder->setOrderingKey('order');
Parameter
NameDescription
orderingKey string

The ordering key.

Returns
TypeDescription
Google\Cloud\PubSub\MessageBuilder

build

Build a message.

Example:

$message = $builder->build();
Returns
TypeDescription
Google\Cloud\PubSub\Message