Cloud PubSub Client - Class MessageBuilder (2.8.0)

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
Name Description
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
Name Description
data string

The message data field.

Returns
Type Description
Google\Cloud\PubSub\MessageBuilder

setAttributes

Set optional attributes for this message.

Example:

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

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

Returns
Type Description
Google\Cloud\PubSub\MessageBuilder

addAttribute

Add a single attribute to the message.

Example:

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

The attribute key.

value string

The attribute value.

Returns
Type Description
Google\Cloud\PubSub\MessageBuilder

setOrderingKey

Set the message's ordering key.

Example:

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

The ordering key.

Returns
Type Description
Google\Cloud\PubSub\MessageBuilder

build

Build a message.

Example:

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