Cloud PubSub Client - Class Topic (1.44.0)

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

A named resource to which messages are sent by publishers.

Example:

use Google\Cloud\PubSub\PubSubClient;

$pubsub = new PubSubClient();
$topic = $pubsub->topic('my-new-topic');
// You can also pass a fully-qualified topic name:
$topic = $pubsub->topic('projects/my-awesome-project/topics/my-new-topic');

Namespace

Google \ Cloud \ PubSub

Methods

__construct

Create a PubSub topic.

Parameters
NameDescription
connection Google\Cloud\PubSub\Connection\ConnectionInterface

A connection to the Google Cloud Platform service

projectId string

The project Id

name string

The topic name

encode bool

Whether messages should be base64 encoded.

info array

A [Topic](https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.topics

↳ name string

The name of the topic.

↳ labels array

Key value pairs used to organize your resources.

↳ kmsKeyName string

The resource name of the Cloud KMS CryptoKey to be used to protect access to messages published on this topic. The expected format is projects/my-project/locations/kr-location/keyRings/my-kr/cryptoKeys/my-key.

↳ enableCompression bool

Flag to enable compression of messages before publishing. Set the flag to true to enable compression. Defaults to false. Messsages are compressed if their total size >= compressionBytesThreshold, whose default value has been experimentally derived after performance evaluations.

↳ compressionBytesThreshold int

The threshold byte size above which messages are compressed. This only takes effect if enableCompression is set to true. Defaults to 240. (This value is experiementally derived after performance evaluations.)

clientConfig array

[optional] Configuration options for the PubSub client used to handle processing of batch items through the daemon. For valid options please see Google\Cloud\PubSub\PubSubClient::__construct(). Defaults to the options provided to the PubSub client associated with this instance.

name

Get the topic name

Example:

echo $topic->name();
Returns
TypeDescription
string

create

Create a topic.

Example:

$topicInfo = $topic->create();
Parameters
NameDescription
options array

Configuration Options

↳ labels array

Key value pairs used to organize your resources.

↳ kmsKeyName string

The resource name of the Cloud KMS CryptoKey to be used to protect access to messages published on this topic. The expected format is projects/my-project/locations/kr-location/keyRings/my-kr/cryptoKeys/my-key.

↳ messageStoragePolicy array

Policy constraining the set of Google Cloud Platform regions where messages published to the topic may be stored. If not present, then no constraints are in effect.

↳ messageStoragePolicy string[]

.allowedPersistenceRegions A list of IDs of GCP regions where messages that are published to the topic may be persisted in storage. Messages published by publishers running in non-allowed GCP regions (or running outside of GCP altogether) will be routed for storage in one of the allowed regions. An empty list means that no regions are allowed, and is not a valid configuration.

↳ schemaSettings string|Schema

.schema The name of a schema that messages published should be validated against, or an instance of Google\Cloud\PubSub\Google\Cloud\PubSub\Schema.

↳ schemaSettings string

.encoding The encoding of messages validated against schema. For allowed values, see constants defined on Google\Cloud\PubSub\Google\Cloud\PubSub\V1\Encoding}. </xref

Returns
TypeDescription
arrayTopic information

update

Update the topic.

Note that the topic's name and kms key name are immutable properties and may not be modified.

Example:

$topic->update([
    'messageStoragePolicy' => [
        'allowedPersistenceRegions' => ['us-central1']
    ]
]);
// Updating labels with an explicit update mask
$topic->update([
    'labels' => [
        'foo' => 'bar'
    ]
], [
    'updateMask' => [
        'labels'
    ]
]);
Parameters
NameDescription
topic array

The Topic data.

↳ labels array

Key value pairs used to organize your resources.

↳ messageStoragePolicy array

Policy constraining the set of Google Cloud Platform regions where messages published to the topic may be stored. If not present, then no constraints are in effect.

↳ messageStoragePolicy string[]

.allowedPersistenceRegions A list of IDs of GCP regions where messages that are published to the topic may be persisted in storage. Messages published by publishers running in non-allowed GCP regions (or running outside of GCP altogether) will be routed for storage in one of the allowed regions. An empty list means that no regions are allowed, and is not a valid configuration.

↳ schemaSettings string|Schema

.schema The name of a schema that messages published should be validated against, or an instance of Google\Cloud\PubSub\Google\Cloud\PubSub\Schema.

↳ schemaSettings string

.encoding The encoding of messages validated against schema. For allowed values, see constants defined on Google\Cloud\PubSub\Google\Cloud\PubSub\V1\Encoding}. </xref

options array

Configuration options.

↳ updateMask array

A list of field paths to be modified. Nested key names should be dot-separated, e.g. messageStoragePolicy.allowedPersistenceRegions. Google Cloud PHP will attempt to infer this value on your behalf, however modification of map fields with arbitrary keys (such as labels or message storage policy) requires an explicit update mask.

Returns
TypeDescription
arrayThe topic info.

delete

Delete a topic.

Example:

$topic->delete();
Parameter
NameDescription
options array

[optional] Configuration Options

Returns
TypeDescription
void

exists

Check if a topic exists.

Service errors will NOT bubble up from this method. It will always return a boolean value. If you want to check for errors, use Google\Cloud\PubSub\Google\Cloud\PubSub\Topic::info().

Example:

if ($topic->exists()) {
    echo 'Topic exists';
}
Parameter
NameDescription
options array

[optional] Configuration Options

Returns
TypeDescription
bool

info

Get topic information.

Currently this resource returns only the topic name, if the topic exists. It is mostly useful therefore for checking if a topic exists.

Since this method will throw an exception if the topic is not found, you may find that Topic::exists() is a better fit for a true/false check.

This method will use the previously cached result, if available. To force a refresh from the API, use Google\Cloud\PubSub\Google\Cloud\PubSub\Topic::reload().

Example:

$info = $topic->info();
echo $info['name']; // projects/my-awesome-project/topics/my-new-topic
Parameter
NameDescription
options array

[optional] Configuration Options

Returns
TypeDescription
array[A representation of a Topic](https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.topics)

reload

Get topic information from the API.

Currently this resource returns only the topic name, if the topic exists. It is mostly useful therefore for checking if a topic exists.

Since this method will throw an exception if the topic is not found, you may find that Topic::exists() is a better fit for a true/false check.

This method will retrieve a new result from the API. To use a previously cached result, if one exists, use Google\Cloud\PubSub\Google\Cloud\PubSub\Topic::info().

Example:

$topic->reload();
$info = $topic->info();
echo $info['name']; // projects/my-awesome-project/topics/my-new-topic
Parameter
NameDescription
options array

[optional] Configuration Options

Returns
TypeDescription
array[A representation of a Topic](https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.topics)

publish

Publish a new message to the topic.

$message must provide at least one of data and attributes members.

Example:

$topic->publish([
    'data' => 'New User Registered',
    'attributes' => [
        'id' => '1',
        'userName' => 'John',
        'location' => 'Detroit'
    ]
]);
Parameters
NameDescription
message Google\Cloud\PubSub\Message|array

An instance of Google\Cloud\PubSub\Google\Cloud\PubSub\Message, or an array in the correct Message Format.

options array

[optional] Configuration Options

Returns
TypeDescription
arrayA list of message IDs

publishBatch

Publish multiple messages at once.

Note that if ordering keys are provided, all members of given messages set must provide the same ordering key. Multiple ordering keys in a single publish call is not supported.

Example:

$topic->publishBatch([
    [
        'data' => 'New User Registered',
        'attributes' => [
            'id' => '1',
            'userName' => 'John',
            'location' => 'Detroit'
        ]
    ], [
        'data' => 'New User Registered',
        'attributes' => [
            'id' => '2',
            'userName' => 'Steve',
            'location' => 'Mountain View'
        ]
    ]
]);
Parameters
NameDescription
messages array<Google\Cloud\PubSub\Message>|array[]

A list of messages. Each message must be in the correct Message Format, or be an instance of Google\Cloud\PubSub\Google\Cloud\PubSub\Message.

options array

[optional] Configuration Options

Returns
TypeDescription
arrayA list of message IDs.

batchPublisher

Push a message into a batch queue, to be processed at a later point.

Example:

$topic->batchPublisher()
    ->publish([
        'data' => 'New User Registered',
        'attributes' => [
            'id' => '2',
            'userName' => 'Dave',
            'location' => 'Detroit'
        ]
    ]);
Parameters
NameDescription
options array

Configuration options.

↳ debugOutput bool

Whether or not to output debug information. Please note debug output currently only applies in CLI based applications. Defaults to false.

↳ debugOutputResource resource

A resource to output debug output to. Defaults to Resource for php://stderr.

↳ batchOptions array

A set of options for a BatchJob. Google\Cloud\Core\Batch\BatchJob::__construct() for more details. Defaults to ['batchSize' => 1000, 'callPeriod' => 2.0, 'numWorkers' => 2].

↳ clientConfig array

Configuration options for the PubSub client used to handle processing of batch items. For valid options please see Google\Cloud\PubSub\PubSubClient::__construct(). Defaults to the options provided to the client associated with the current Topic instance.

↳ batchRunner BatchRunner

A BatchRunner object. Mainly used for the tests to inject a mock. Defaults to a newly created BatchRunner.

↳ identifier string

An identifier for the batch job. Defaults to pubsub-topic-{topic-name}. Example: pubsub-topic-mytopic.

↳ closureSerializer ClosureSerializerInterface

An implementation responsible for serializing closures used in the $clientConfig. This is especially important when using the batch daemon. Defaults to Google\Cloud\PubSub\Google\Cloud\Core\Batch\OpisClosureSerializer if the opis/closure library is installed.

↳ enableCompression bool

Flag to enable compression of messages before publishing. Set the flag to true to enable compression. Defaults to false. Messsages are compressed if their total size >= compressionBytesThreshold, whose default value has been experimentally derived after performance evaluations.

↳ compressionBytesThreshold int

The threshold byte size above which messages are compressed. This only takes effect if enableCompression is set to true. Defaults to 240. (This value is experiementally derived after performance evaluations.)

Returns
TypeDescription
Google\Cloud\PubSub\BatchPublisher

subscribe

Create a subscription to the topic.

Example:

$subscription = $topic->subscribe('my-new-subscription');
Parameters
NameDescription
name string

The subscription name

options array

[optional] Please see Google\Cloud\PubSub\Google\Cloud\PubSub\Subscription::create() for configuration details.

Returns
TypeDescription
Google\Cloud\PubSub\Subscription

subscription

This method will not run any API requests. You will receive a Subscription object that you can use to interact with the API.

Example:

$subscription = $topic->subscription('my-new-subscription');
Parameter
NameDescription
name string

The subscription name

Returns
TypeDescription
Google\Cloud\PubSub\Subscription

subscriptions

Retrieve a list of active subscriptions to the current topic.

Example:

$subscriptions = $topic->subscriptions();
foreach ($subscriptions as $subscription) {
    echo $subscription->name();
}
Parameters
NameDescription
options array

Configuration Options

↳ pageSize int

Maximum number of subscriptions to return.

↳ resultLimit int

Limit the number of results returned in total. Defaults to 0 (return all results).

↳ pageToken string

A previously-returned page token used to resume the loading of results from a specific point.

Returns
TypeDescription
Google\Cloud\Core\Iterator\ItemIterator<\google\cloud\pubsub\subscription>

iam

Manage the IAM policy for the current Topic.

Example:

$iam = $topic->iam();
Returns
TypeDescription
Google\Cloud\Core\Iam\Iam

__debugInfo

Present a nicer debug result to people using php 5.6 or greater.

Returns
TypeDescription
array

Constants

DEFAULT_COMPRESSION_BYTES_THRESHOLD

Value: 240

DEFAULT_ENABLE_COMPRESSION

Value: false