Reference documentation and code samples for the Cloud PubSub Client class PubSubClient.
Google Cloud Pub/Sub allows you to send and receive messages between independent applications. Find more information at the Google Cloud Pub/Sub docs.
To enable the Google Cloud Pub/Sub Emulator,
set the PUBSUB_EMULATOR_HOST
environment variable.
This client supports transport over REST or gRPC.
In order to enable gRPC support please make sure to install and enable the gRPC extension through PECL:
$ pecl install grpc
```php
NOTE: Support for gRPC is currently at an Alpha quality level, meaning it is still
a work in progress and is more likely to get backwards-incompatible updates.
When using gRPC in production environments, it is highly recommended that you make use of the
Protobuf PHP extension for improved performance. Protobuf can be installed
via [PECL](https://pecl.php.net).
$ pecl install protobuf
Example:
use Google\Cloud\PubSub\PubSubClient;
$pubsub = new PubSubClient();
// Using the Pub/Sub Emulator use Google\Cloud\PubSub\PubSubClient;
// Be sure to use the port specified when starting the emulator.
// 8900
is used as an example only.
putenv('PUBSUB_EMULATOR_HOST=localhost:8900');
$pubsub = new PubSubClient(); ```
Methods
__construct
Create a PubSub client.
Parameters | |
---|---|
Name | Description |
config |
array
Configuration Options. |
↳ apiEndpoint |
string
The hostname with optional port to use in place of the default service endpoint. Example: |
↳ projectId |
string
The project ID from the Google Developer's Console. |
↳ authCache |
CacheItemPoolInterface
A cache for storing access tokens. Defaults to a simple in memory implementation. |
↳ authCacheOptions |
array
Cache configuration options. |
↳ authHttpHandler |
callable
A handler used to deliver Psr7 requests specifically for authentication. |
↳ credentialsFetcher |
FetchAuthTokenInterface
A credentials fetcher instance. |
↳ httpHandler |
callable
A handler used to deliver Psr7 requests. Only valid for requests sent over REST. |
↳ keyFile |
array
The contents of the service account credentials .json file retrieved from the Google Developer's Console. Ex: |
↳ keyFilePath |
string
The full path to your service account credentials .json file retrieved from the Google Developers Console. |
↳ requestTimeout |
float
Seconds to wait before timing out the request. Defaults to |
↳ retries |
int
Number of retries for a failed request. Defaults to |
↳ scopes |
array
Scopes to be used for the request. |
↳ quotaProject |
string
Specifies a user project to bill for access charges associated with the request. |
↳ transport |
string
The transport type used for requests. May be either |
createTopic
Create a topic.
Unlike Google\Cloud\PubSub\Google\Cloud\PubSub\PubSubClient::topic(), this method will send an API call to create the topic. If the topic already exists, an exception will be thrown. When in doubt, use Google\Cloud\PubSub\Google\Cloud\PubSub\PubSubClient::topic().
Example:
$topic = $pubsub->createTopic('my-new-topic');
echo $topic->info()['name']; // `projects/my-awesome-project/topics/my-new-topic`
Parameters | |
---|---|
Name | Description |
name |
string
The topic name |
options |
array
[optional] Configuration Options. For available configuration options, refer to {@see \Google\Cloud\PubSub\Google\Cloud\PubSub\Topic::create()}. |
Returns | |
---|---|
Type | Description |
Google\Cloud\PubSub\Topic |
topic
Lazily instantiate a topic with a topic name.
No API requests are made by this method. If you want to create a new topic, use Google\Cloud\PubSub\Google\Cloud\PubSub\Topic::createTopic().
Example:
// No API request yet!
$topic = $pubsub->topic('my-new-topic');
// This will execute an API call.
echo $topic->info()['name']; // `projects/my-awesome-project/topics/my-new-topic`
Parameter | |
---|---|
Name | Description |
name |
string
The topic name |
Returns | |
---|---|
Type | Description |
Google\Cloud\PubSub\Topic |
topics
Get a list of the topics registered to your project.
Example:
$topics = $pubsub->topics();
foreach ($topics as $topic) {
$info = $topic->info();
echo $info['name']; // `projects/my-awesome-project/topics/my-new-topic`
}
Parameters | |
---|---|
Name | Description |
options |
array
Configuration Options |
↳ pageSize |
int
Maximum number of results to return per request. |
↳ resultLimit |
int
Limit the number of results returned in total. Defaults to |
↳ pageToken |
string
A previously-returned page token used to resume the loading of results from a specific point. |
Returns | |
---|---|
Type | Description |
Google\Cloud\Core\Iterator\ItemIterator<\google\cloud\pubsub\topic> |
subscribe
Create a Subscription. If the subscription does not exist, it will be created.
Use Google\Cloud\PubSub\Google\Cloud\PubSub\PubSubClient::subscription() to create a subscription object without any API requests. If the topic already exists, an exception will be thrown. When in doubt, use Google\Cloud\PubSub\Google\Cloud\PubSub\PubSubClient::subscription().
Example:
// Create a subscription. If it doesn't exist in the API, it will be created.
$subscription = $pubsub->subscribe('my-new-subscription', 'my-topic-name');
Parameters | |
---|---|
Name | Description |
name |
string
A subscription name |
topic |
Google\Cloud\PubSub\Topic|string
The topic to which the new subscription will be subscribed. |
options |
array
[optional] Please see {@see \Google\Cloud\PubSub\Google\Cloud\PubSub\Subscription::create()} for configuration details. |
Returns | |
---|---|
Type | Description |
Google\Cloud\PubSub\Subscription |
subscription
Lazily instantiate a subscription with a subscription name.
This method will NOT perform any API calls. If you wish to create a new subscription, use Google\Cloud\PubSub\Google\Cloud\PubSub\PubSubClient::subscribe().
Unless you are sure the subscription exists, you should check its existence before using it.
Example:
$subscription = $pubsub->subscription('my-new-subscription');
Parameters | |
---|---|
Name | Description |
name |
string
The subscription name |
topicName |
string
[optional] The topic name |
Returns | |
---|---|
Type | Description |
Google\Cloud\PubSub\Subscription |
subscriptions
Get a list of the subscriptions registered to all of your project's topics.
Example:
$subscriptions = $pubsub->subscriptions();
foreach ($subscriptions as $subscription) {
$info = $subscription->info();
echo $info['name']; // `projects/my-awesome-project/subscriptions/<subscription-name>`
}
Parameters | |
---|---|
Name | Description |
options |
array
Configuration Options |
↳ pageSize |
int
Maximum number of results to return per request. |
↳ resultLimit |
int
Limit the number of results returned in total. Defaults to |
↳ pageToken |
string
A previously-returned page token used to resume the loading of results from a specific point. |
Returns | |
---|---|
Type | Description |
Google\Cloud\Core\Iterator\ItemIterator<\google\cloud\pubsub\subscription> |
createSnapshot
Create a snapshot.
Please note that this method may not yet be available in your project.
Example:
$subscription = $pubsub->subscription($subscriptionName);
$snapshot = $pubsub->createSnapshot('my-snapshot', $subscription);
Parameters | |
---|---|
Name | Description |
name |
string
The snapshot name. |
subscription |
Google\Cloud\PubSub\Subscription
The subscription to take a snapshot of. |
options |
array
[optional] Configuration options. |
Returns | |
---|---|
Type | Description |
Google\Cloud\PubSub\Snapshot |
snapshot
Lazily create a snapshot instance.
Example:
$snapshot = $pubsub->snapshot('my-snapshot');
Parameters | |
---|---|
Name | Description |
name |
string
The snapshot name. |
info |
array
[optional] Snapshot info. |
Returns | |
---|---|
Type | Description |
Google\Cloud\PubSub\Snapshot |
snapshots
Get a list of the snapshots in the project.
Please note that this method may not yet be available in your project.
Example:
$snapshots = $pubsub->snapshots();
foreach ($snapshots as $snapshot) {
$info = $snapshot->info();
echo $info['name'];
}
Parameters | |
---|---|
Name | Description |
options |
array
Configuration Options |
↳ pageSize |
int
Maximum number of results to return per request. |
↳ resultLimit |
int
Limit the number of results returned in total. Defaults to |
↳ pageToken |
string
A previously-returned page token used to resume the loading of results from a specific point. |
Returns | |
---|---|
Type | Description |
Google\Cloud\Core\Iterator\ItemIterator<\google\cloud\pubsub\snapshot> |
schema
Lazily instantiate a schema object.
Example:
$schema = $pubsub->schema('my-schema');
Parameters | |
---|---|
Name | Description |
schemaId |
string
The schema ID. Must exist in the current project. |
info |
array
[optional] The schema resource info. |
Returns | |
---|---|
Type | Description |
Google\Cloud\PubSub\Schema |
createSchema
Creates and returns a new schema.
Example:
$definition = file_get_contents('my-schema.txt');
$schema = $pubsub->createSchema('my-schema', 'AVRO', $definition);
Parameters | |
---|---|
Name | Description |
schemaId |
string
The desired schema ID. |
type |
string
The schema type. Allowed values are |
definition |
string
The definition of the schema. This should
contain a string representing the full definition of the schema that
is a valid schema definition of the type specified in |
options |
array
[optional] Configuration options |
Returns | |
---|---|
Type | Description |
Google\Cloud\PubSub\Schema |
schemas
Lists all schemas in the current project.
Please note that the schemas returned will not contain the entire resource.
If you need details on the full resource, call Google\Cloud\PubSub\Google\Cloud\PubSub\Schema::reload()
on the resource in question, or set $options.view
to FULL
.
Example:
$schemas = $pubsub->schemas();
foreach ($schemas as $schema) {
$info = $schema->info();
echo $info['name']; // `projects/my-awesome-project/schemas/my-new-schema`
}
Parameters | |
---|---|
Name | Description |
options |
array
Configuration Options |
↳ view |
string
The set of Schema fields to return in the response. If not set, returns Schemas with |
↳ pageSize |
int
Maximum number of results to return per request. |
↳ resultLimit |
int
Limit the number of results returned in total. Defaults to |
↳ pageToken |
string
A previously-returned page token used to resume the loading of results from a specific point. |
Returns | |
---|---|
Type | Description |
Google\Cloud\Core\Iterator\ItemIterator<\google\cloud\pubsub\schema> |
validateSchema
Verify that a schema is valid.
If the schema is valid, the response will be empty. If invalid, a Google\Cloud\PubSub\Google\Cloud\Core\Exception\BadRequestException will be thrown.
Example:
use Google\Cloud\Core\Exception\BadRequestException;
$definition = file_get_contents('my-schema.txt');
try {
$pubsub->validateSchema([
'type' => 'AVRO',
'definition' => $definition
]);
echo "schema is valid!";
} catch (BadRequestException $e) {
echo $e->getMessage();
}
Parameters | |
---|---|
Name | Description |
schema |
array
The schema to validate. See Schema for available parameters. |
options |
array
[optional] Configuration options |
Returns | |
---|---|
Type | Description |
void |
validateMessage
Validate a given message against a schema.
If the message is valid, the response will be empty. If invalid, a Google\Cloud\PubSub\Google\Cloud\Core\Exception\BadRequestException will be thrown.
Example:
use Google\Cloud\Core\Exception\BadRequestException;
$schema = $pubsub->schema('my-schema');
try {
$pubsub->validateMessage($schema, $message, 'JSON');
echo "message is valid!";
} catch (BadRequestException $e) {
echo $e->getMessage();
}
Parameters | |
---|---|
Name | Description |
schema |
Google\Cloud\PubSub\Schema|string|array
The schema to validate against. If a
string is given, it should be a fully-qualified schema name, e.g.
|
message |
string
The base64 encoded message to validate. |
encoding |
string
Either |
options |
array
[optional] Configuration options |
Returns | |
---|---|
Type | Description |
void |
consume
Consume an incoming message and return a PubSub Message.
This method is for use with push delivery only.
Example:
$httpPostRequestBody = file_get_contents('php://input');
$requestData = json_decode($httpPostRequestBody, true);
$message = $pubsub->consume($requestData);
Parameter | |
---|---|
Name | Description |
requestData |
array
|
Returns | |
---|---|
Type | Description |
Google\Cloud\PubSub\Message |
timestamp
Create a Timestamp object.
Example:
$timestamp = $pubsub->timestamp(new \DateTime('2003-02-05 11:15:02.421827Z'));
Parameters | |
---|---|
Name | Description |
timestamp |
DateTimeInterface
|
nanoSeconds |
int
[optional] The number of nanoseconds in the timestamp. |
Returns | |
---|---|
Type | Description |
Google\Cloud\Core\Timestamp |
duration
Create a Duration object.
Example:
$duration = $pubsub->duration(100, 00001);
Parameters | |
---|---|
Name | Description |
seconds |
int
The number of seconds in the duration. |
nanos |
int
[optional] The number of nanoseconds in the duration.
Defaults to |
Returns | |
---|---|
Type | Description |
Google\Cloud\Core\Duration |
__debugInfo
Constants
VERSION
Value: '1.42.1'
FULL_CONTROL_SCOPE
Value: 'https://www.googleapis.com/auth/pubsub'