Skip to content

Repository files navigation

Google Cloud PHP Client

Idiomatic PHP client for Google Cloud Platform services.

Latest Stable VersionPackagistTravis Build Statuscodecov

This client supports the following Google Cloud Platform services at a General Availability quality level:

This client supports the following Google Cloud Platform services at a Beta quality level:

This client supports the following Google Cloud Platform services at an Alpha quality level:

If you need support for other Google APIs, please check out the Google APIs Client Library for PHP.

Quick Start

We recommend installing individual component packages when possible. A list of available packages can be found on Packagist.

For example:

$ composer require google/cloud-bigquery
$ composer require google/cloud-datastore

We also provide the google/cloud package, which includes all Google Cloud clients.

$ composer require google/cloud

Authentication

Authentication is handled by the client library automatically. You just need to provide the authentication details when creating a client. Generally, authentication is accomplished using a Service Account. For more information on obtaining Service Account credentials, see our Authentication Guide.

Once you've obtained your credentials file, it may be used to create an authenticated client.

require'vendor/autoload.php';
useGoogle\Cloud\Core\ServiceBuilder;
// Authenticate using a keyfile path$cloud = newServiceBuilder([
'keyFilePath' => 'path/to/keyfile.json'
]);
// Authenticate using keyfile data$cloud = newServiceBuilder([
'keyFile' => json_decode(file_get_contents('/path/to/keyfile.json'), true)
]);

If you do not wish to embed your authentication information in your application code, you may also make use of Application Default Credentials.

require'vendor/autoload.php';
useGoogle\Cloud\Core\ServiceBuilder;
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/keyfile.json');
$cloud = newServiceBuilder();

The GOOGLE_APPLICATION_CREDENTIALS environment variable may be set in your server configuration.

Google Cloud Datastore (GA)

Preview

require'vendor/autoload.php';
useGoogle\Cloud\Datastore\DatastoreClient;
$datastore = newDatastoreClient([
'projectId' => 'my_project'
]);
// Create an entity$bob = $datastore->entity('Person');
$bob['firstName'] = 'Bob';
$bob['email'] = 'bob@example.com';
$datastore->insert($bob);
// Update the entity$bob['email'] = 'bobV2@example.com';
$datastore->update($bob);
// If you know the ID of the entity, you can look it up$key = $datastore->key('Person', '12345328897844');
$entity = $datastore->lookup($key);

google/cloud-datastore

Google Cloud Datastore can be installed separately by requiring the google/cloud-datastore composer package:

$ composer require google/cloud-datastore

Google Cloud Storage (GA)

Preview

require'vendor/autoload.php';
useGoogle\Cloud\Storage\StorageClient;
$storage = newStorageClient([
'projectId' => 'my_project'
]);
$bucket = $storage->bucket('my_bucket');
// Upload a file to the bucket.$bucket->upload(
fopen('/data/file.txt', 'r')
);
// Using Predefined ACLs to manage object permissions, you may// upload a file and give read access to anyone with the URL.$bucket->upload(
fopen('/data/file.txt', 'r'),
[
'predefinedAcl' => 'publicRead'
]
);
// Download and store an object from the bucket locally.$object = $bucket->object('file_backup.txt');
$object->downloadToFile('/data/file_backup.txt');

Stream Wrapper

require'vendor/autoload.php';
useGoogle\Cloud\Storage\StorageClient;
$storage = newStorageClient([
'projectId' => 'my_project'
]);
$storage->registerStreamWrapper();
$contents = file_get_contents('gs://my_bucket/file_backup.txt');

google/cloud-storage

Google Cloud Storage can be installed separately by requiring the google/cloud-storage composer package:

$ composer require google/cloud-storage

Google Cloud Translation (GA)

Preview

require'vendor/autoload.php';
useGoogle\Cloud\Translate\TranslateClient;
$translate = newTranslateClient([
'key' => 'your_key'
]);
// Translate text from english to french.$result = $translate->translate('Hello world!', [
'target' => 'fr'
]);
echo$result['text'] . "\n";
// Detect the language of a string.$result = $translate->detectLanguage('Greetings from Michigan!');
echo$result['languageCode'] . "\n";
// Get the languages supported for translation specifically for your target language.$languages = $translate->localizedLanguages([
'target' => 'en'
]);
foreach ($languagesas$language) {
echo$language['name'] . "\n";
echo$language['code'] . "\n";
}
// Get all languages supported for translation.$languages = $translate->languages();
foreach ($languagesas$language) {
echo$language . "\n";
}

google/cloud-translate

Google Cloud Translation can be installed separately by requiring the google/cloud-translate composer package:

$ composer require google/cloud-translate

Google Stackdriver Logging (GA)

Preview

require'vendor/autoload.php';
useGoogle\Cloud\Logging\LoggingClient;
$logging = newLoggingClient([
'projectId' => 'my_project'
]);
// Get a logger instance.$logger = $logging->logger('my_log');
// Write a log entry.$logger->write('my message');
// List log entries from a specific log.$entries = $logging->entries([
'filter' => 'logName = projects/my_project/logs/my_log'
]);
foreach ($entriesas$entry) {
echo$entry->info()['textPayload'] . "\n";
}

google/cloud-logging

Google Stackdriver Logging can be installed separately by requiring the google/cloud-logging composer package:

$ composer require google/cloud-logging

Cloud Firestore (Beta)

Preview

require'vendor/autoload.php';
useGoogle\Cloud\Firestore\FirestoreClient;
$firestore = newFirestoreClient([
'projectId' => 'my_project'
]);
$collectionReference = $firestore->collection('Users');
$documentReference = $collectionReference->document($userId);
$snapshot = $documentReference->snapshot();
echo"Hello " . $snapshot['firstName'];

google/cloud-firestore

Cloud Firestore can be installed separately by requiring the google/cloud-firestore composer package:

$ composer require google/cloud-firestore

Cloud Spanner (Beta)

Preview

require'vendor/autoload.php';
useGoogle\Cloud\Spanner\SpannerClient;
$spanner = newSpannerClient([
'projectId' => 'my_project'
]);
$db = $spanner->connect('my-instance', 'my-database');
$userQuery = $db->execute('SELECT * FROM Users WHERE id = @id', [
'parameters' => [
'id' => $userId
]
]);
$user = $userQuery->rows()->current();
echo'Hello ' . $user['firstName'];

google/cloud-spanner

Cloud Spanner can be installed separately by requiring the google/cloud-spanner composer package:

$ composer require google/cloud-spanner

Google BigQuery (Beta)

Preview

require'vendor/autoload.php';
useGoogle\Cloud\BigQuery\BigQueryClient;
$bigQuery = newBigQueryClient([
'projectId' => 'my_project'
]);
// Get an instance of a previously created table.$dataset = $bigQuery->dataset('my_dataset');
$table = $dataset->table('my_table');
// Begin a job to import data from a CSV file into the table.$job = $table->load(
fopen('/data/my_data.csv', 'r')
);
// Run a query and inspect the results.$queryResults = $bigQuery->runQuery('SELECT * FROM [my_project:my_dataset.my_table]');
foreach ($queryResults->rows() as$row) {
print_r($row);
}

google/cloud-bigquery

Google BigQuery can be installed separately by requiring the google/cloud-bigquery composer package:

$ composer require google/cloud-bigquery

Google Cloud Natural Language (Beta)

Preview

require'vendor/autoload.php';
useGoogle\Cloud\Language\LanguageClient;
$language = newLanguageClient([
'projectId' => 'my_project'
]);
// Analyze a sentence.$annotation = $language->annotateText('Greetings from Michigan!');
// Check the sentiment.if ($annotation->sentiment() > 0) {
echo"This is a positive message.\n";
}
// Detect entities.$entities = $annotation->entitiesByType('LOCATION');
foreach ($entitiesas$entity) {
echo$entity['name'] . "\n";
}
// Parse the syntax.$tokens = $annotation->tokensByTag('NOUN');
foreach ($tokensas$token) {
echo$token['text']['content'] . "\n";
}

google/cloud-language

Google Cloud Natural Language can be installed separately by requiring the google/cloud-language composer package:

$ composer require google/cloud-language

Google Cloud Pub/Sub (Beta)

Preview

require'vendor/autoload.php';
useGoogle\Cloud\PubSub\PubSubClient;
$pubSub = newPubSubClient([
'projectId' => 'my_project'
]);
// Get an instance of a previously created topic.$topic = $pubSub->topic('my_topic');
// Publish a message to the topic.$topic->publish([
'data' => 'My new message.',
'attributes' => [
'location' => 'Detroit'
]
]);
// Get an instance of a previously created subscription.$subscription = $pubSub->subscription('my_subscription');
// Pull all available messages.$messages = $subscription->pull();
foreach ($messagesas$message) {
echo$message->data() . "\n";
echo$message->attribute('location');
}

google/cloud-pubsub

Google Cloud Pub/Sub can be installed separately by requiring the google/cloud-pubsub composer package:

$ composer require google/cloud-pubsub

Google Cloud Video Intelligence (Beta)

Preview

require__DIR__ . '/vendor/autoload.php';
useGoogle\Cloud\VideoIntelligence\V1\VideoIntelligenceServiceClient;
useGoogle\Cloud\VideoIntelligence\V1\Feature;
$videoIntelligenceServiceClient = newVideoIntelligenceServiceClient();
$inputUri = "gs://example-bucket/example-video.mp4";
$features = [
Feature::LABEL_DETECTION,
];
$operationResponse = $videoIntelligenceServiceClient->annotateVideo($inputUri, $features);
$operationResponse->pollUntilComplete();
if ($operationResponse->operationSucceeded()) {
$results = $operationResponse->getResult();
foreach ($results->getAnnotationResultsList() as$result) {
foreach ($result->getLabelAnnotationsList() as$labelAnnotation) {
echo"Label: " . $labelAnnotation->getDescription() . "\n";
}
}
} else {
$error = $operationResponse->getError();
echo"error: " . $error->getMessage() . "\n";
}

google/cloud-videointelligence

Cloud Video Intelligence can be installed separately by requiring the google/cloud-videointelligence composer package:

$ composer require google/cloud-videointelligence

Google Cloud Vision (Beta)

Preview

require'vendor/autoload.php';
useGoogle\Cloud\Vision\VisionClient;
$vision = newVisionClient([
'projectId' => 'my_project'
]);
// Annotate an image, detecting faces.$image = $vision->image(
fopen('/data/family_photo.jpg', 'r'),
['faces']
);
$annotation = $vision->annotate($image);
// Determine if the detected faces have headwear.foreach ($annotation->faces() as$key => $face) {
if ($face->hasHeadwear()) {
echo"Face $key has headwear.\n";
}
}

google/cloud-vision

Google Cloud Vision can be installed separately by requiring the google/cloud-vision composer package:

$ composer require google/cloud-vision

Google DLP (Beta)

Preview

require'vendor/autoload.php';
useGoogle\Cloud\Dlp\V2beta1\DlpServiceClient;
useGoogle\Cloud\Dlp\V2beta1\ContentItem;
useGoogle\Cloud\Dlp\V2beta1\InfoType;
useGoogle\Cloud\Dlp\V2beta1\InspectConfig;
$dlpServiceClient = newDlpServiceClient();
$name = 'EMAIL_ADDRESS';
$infoTypesElement = newInfoType();
$infoTypesElement->setName($name);
$infoTypes = [$infoTypesElement];
$inspectConfig = newInspectConfig();
$inspectConfig->setInfoTypes($infoTypes);
$type = 'text/plain';
$value = 'My email is example@example.com.';
$itemsElement = newContentItem();
$itemsElement->setType($type);
$itemsElement->setValue($value);
$items = [$itemsElement];
try {
$response = $dlpServiceClient->inspectContent($inspectConfig, $items);
} finally {
$dlpServiceClient->close();
}

google/cloud-dlp

Google DLP can be installed separately by requiring the google/cloud-dlp composer package:

$ composer require google/cloud-dlp

Google Stackdriver Error Reporting (Beta)

Preview

require'vendor/autoload.php';
useGoogle\Cloud\ErrorReporting\V1beta1\ReportErrorsServiceClient;
useGoogle\Cloud\ErrorReporting\\V1beta1\ReportedErrorEvent;
$reportErrorsServiceClient = newReportErrorsServiceClient();
$formattedProjectName = $reportErrorsServiceClient->projectName('[PROJECT]');
$event = newReportedErrorEvent();
try {
$response = $reportErrorsServiceClient->reportErrorEvent($formattedProjectName, $event);
} finally {
$reportErrorsServiceClient->close();
}

google/cloud-error-reporting

Google Stackdriver Error Reporting can be installed separately by requiring the google/cloud-error-reporting composer package:

$ composer require google/cloud-error-reporting

Google Stackdriver Monitoring (Beta)

Preview

require'vendor/autoload.php';
<?phpuseGoogle\Api\Metric;
useGoogle\Api\MonitoredResource;
useGoogle\Cloud\Monitoring\V3\MetricServiceClient;
useGoogle\Cloud\Monitoring\V3\Point;
useGoogle\Cloud\Monitoring\V3\TimeInterval;
useGoogle\Cloud\Monitoring\V3\TimeSeries;
useGoogle\Cloud\Monitoring\V3\TypedValue;
useGoogle\Protobuf\Timestamp;
$metricServiceClient = newMetricServiceClient();
$formattedProjectName = $metricServiceClient->projectName($projectId);
$labels = [
'instance_id' => $instanceId,
'zone' => $zone,
];
$m = newMetric();
$m->setType('custom.googleapis.com/my_metric');
$r = newMonitoredResource();
$r->setType('gce_instance');
$r->setLabels($labels);
$value = newTypedValue();
$value->setDoubleValue(3.14);
$timestamp = newTimestamp();
$timestamp->setSeconds(time());
$interval = newTimeInterval();
$interval->setStartTime($timestamp);
$interval->setEndTime($timestamp);
$point = newPoint();
$point->setValue($value);
$point->setInterval($interval);
$points = [$point];
$timeSeries = newTimeSeries();
$timeSeries->setMetric($m);
$timeSeries->setResource($r);
$timeSeries->setPoints($points);
try {
$metricServiceClient->createTimeSeries($formattedProjectName, [$timeSeries]);
print('Successfully submitted a time series' . PHP_EOL);
} finally {
$metricServiceClient->close();
}

google/cloud-monitoring

Google Stackdriver Monitoring can be installed separately by requiring the google/cloud-monitoring composer package:

$ composer require google/cloud-monitoring

Google Cloud Speech (Alpha)

Preview

require'vendor/autoload.php';
useGoogle\Cloud\Speech\SpeechClient;
$speech = newSpeechClient([
'projectId' => 'my_project',
'languageCode' => 'en-US'
]);
// Recognize the speech in an audio file.$results = $speech->recognize(
fopen(__DIR__ . '/audio_sample.flac', 'r')
);
foreach ($resultsas$result) {
echo$result->topAlternative()['transcript'] . "\n";
}

google/cloud-speech

Google Cloud Speech can be installed separately by requiring the google/cloud-speech composer package:

$ composer require google/cloud-speech

Google Stackdriver Trace (Alpha)

Preview

require'vendor/autoload.php';
useGoogle\Cloud\Trace\TraceClient;
$traceClient = newTraceClient([
'projectId' => 'my_project'
]);
// Create a Trace$trace = $traceClient->trace();
$span = $trace->span([
'name' => 'main'
]);
$span->setStart();
$span->setEnd();
$trace->setSpans([$span]);
$traceClient->insert($trace);
// List recent Tracesforeach($traceClient->traces() as$trace) {
var_dump($trace->traceId());
}

google/cloud-trace

Stackdriver Trace can be installed separately by requiring the google/cloud-trace composer package:

$ composer require google/cloud-trace

Caching Access Tokens

By default the library will use a simple in-memory caching implementation, however it is possible to override this behavior by passing a PSR-6 caching implementation in to the desired client.

The following example takes advantage of Symfony's Cache Component.

require'vendor/autoload.php';
useGoogle\Cloud\Storage\StorageClient;
useSymfony\Component\Cache\Adapter\ArrayAdapter;
// Please take the proper precautions when storing your access tokens in a cache no matter the implementation.$cache = newArrayAdapter();
$storage = newStorageClient([
'authCache' => $cache
]);

Versioning

This library follows Semantic Versioning.

Please note it is currently under active development. Any release versioned 0.x.y is subject to backwards incompatible changes at any time.

GA: Libraries defined at a GA quality level are stable, and will not introduce backwards-incompatible changes in any minor or patch releases. We will address issues and requests with the highest priority.

Beta: Libraries defined at a Beta quality level are expected to be mostly stable and we're working towards their release candidate. We will address issues and requests with a higher priority.

Alpha: Libraries defined at an Alpha quality level are still a work-in-progress and are more likely to get backwards-incompatible updates.

Contributing

Contributions to this library are always welcome and highly encouraged.

See CONTRIBUTING for more information on how to get started.

License

Apache 2.0 - See LICENSE for more information.

About

Google Cloud Client Library for PHP

Resources

Code of conduct

Contributing

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages