GoogleCloudPlatform/google-cloud-php

Name: google-cloud-php

Owner: Google Cloud Platform

Description: Google Cloud Client Library for PHP

Created: 2015-10-04 16:09:46.0

Updated: 2018-05-24 06:10:03.0

Pushed: 2018-05-23 18:01:14.0

Homepage: https://googlecloudplatform.github.io/google-cloud-php

Size: 12001

Language: PHP

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

Google Cloud PHP Client

Idiomatic PHP client for Google Cloud Platform services.

Latest Stable Version Packagist Travis Build Status codecov

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:

mposer require google/cloud-bigquery
mposer require google/cloud-datastore

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

mposer 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.

ire 'vendor/autoload.php';

Google\Cloud\Core\ServiceBuilder;

uthenticate using a keyfile path
ud = new ServiceBuilder([
'keyFilePath' => 'path/to/keyfile.json'


uthenticate using keyfile data
ud = new ServiceBuilder([
'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.

ire 'vendor/autoload.php';

Google\Cloud\Core\ServiceBuilder;

nv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/keyfile.json');

ud = new ServiceBuilder();

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

gRPC and Protobuf

Many clients in Google Cloud PHP offer support for gRPC, either as an option or a requirement. gRPC is a high-performance RPC framework created by Google. To use gRPC in PHP, you must install the gRPC PHP extension on your server. While not required, it is also recommended that you install the protobuf extension whenever using gRPC in production.

cl install grpc
cl install protobuf
Cloud Spanner (GA)
Preview
ire 'vendor/autoload.php';

Google\Cloud\Spanner\SpannerClient;

nner = new SpannerClient([
'projectId' => 'my_project'


= $spanner->connect('my-instance', 'my-database');

rQuery = $db->execute('SELECT * FROM Users WHERE id = @id', [
'parameters' => [
    'id' => $userId
]


r = $userQuery->rows()->current();

 'Hello ' . $user['firstName'];
google/cloud-spanner

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

mposer require google/cloud-spanner
Google BigQuery (GA)
Preview
ire 'vendor/autoload.php';

Google\Cloud\BigQuery\BigQueryClient;

Query = new BigQueryClient([
'projectId' => 'my_project'


et an instance of a previously created table.
aset = $bigQuery->dataset('my_dataset');
le = $dataset->table('my_table');

egin a job to import data from a CSV file into the table.
 = $table->load(
fopen('/data/my_data.csv', 'r')


un a query and inspect the results.
ryResults = $bigQuery->runQuery('SELECT * FROM [my_project:my_dataset.my_table]');

ach ($queryResults->rows() as $row) {
print_r($row);

google/cloud-bigquery

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

mposer require google/cloud-bigquery
Google Cloud Datastore (GA)
Preview
ire 'vendor/autoload.php';

Google\Cloud\Datastore\DatastoreClient;

astore = new DatastoreClient([
'projectId' => 'my_project'


reate an entity
 = $datastore->entity('Person');
['firstName'] = 'Bob';
['email'] = 'bob@example.com';
astore->insert($bob);

pdate the entity
['email'] = 'bobV2@example.com';
astore->update($bob);

f you know the ID of the entity, you can look it up
 = $datastore->key('Person', '12345328897844');
ity = $datastore->lookup($key);
google/cloud-datastore

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

mposer require google/cloud-datastore
Google Cloud Pub/Sub (GA)
Preview
ire 'vendor/autoload.php';

Google\Cloud\PubSub\PubSubClient;

Sub = new PubSubClient([
'projectId' => 'my_project'


et an instance of a previously created topic.
ic = $pubSub->topic('my_topic');

ublish a message to the topic.
ic->publish([
'data' => 'My new message.',
'attributes' => [
    'location' => 'Detroit'
]


et an instance of a previously created subscription.
scription = $pubSub->subscription('my_subscription');

ull all available messages.
sages = $subscription->pull();

ach ($messages as $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:

mposer require google/cloud-pubsub
Google Cloud Storage (GA)
Preview
ire 'vendor/autoload.php';

Google\Cloud\Storage\StorageClient;

rage = new StorageClient([
'projectId' => 'my_project'


ket = $storage->bucket('my_bucket');

pload a file to the bucket.
ket->upload(
fopen('/data/file.txt', 'r')


sing Predefined ACLs to manage object permissions, you may
pload a file and give read access to anyone with the URL.
ket->upload(
fopen('/data/file.txt', 'r'),
[
    'predefinedAcl' => 'publicRead'
]


ownload and store an object from the bucket locally.
ect = $bucket->object('file_backup.txt');
ect->downloadToFile('/data/file_backup.txt');
Stream Wrapper
ire 'vendor/autoload.php';

Google\Cloud\Storage\StorageClient;

rage = new StorageClient([
'projectId' => 'my_project'

rage->registerStreamWrapper();

tents = 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:

mposer require google/cloud-storage
Google Cloud Translation (GA)
Preview
ire 'vendor/autoload.php';

Google\Cloud\Translate\TranslateClient;

nslate = new TranslateClient([
'key' => 'your_key'


ranslate text from english to french.
ult = $translate->translate('Hello world!', [
'target' => 'fr'


 $result['text'] . "\n";

etect the language of a string.
ult = $translate->detectLanguage('Greetings from Michigan!');

 $result['languageCode'] . "\n";

et the languages supported for translation specifically for your target language.
guages = $translate->localizedLanguages([
'target' => 'en'


ach ($languages as $language) {
echo $language['name'] . "\n";
echo $language['code'] . "\n";


et all languages supported for translation.
guages = $translate->languages();

ach ($languages as $language) {
echo $language . "\n";

google/cloud-translate

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

mposer require google/cloud-translate
Google Stackdriver Logging (GA)
Preview
ire 'vendor/autoload.php';

Google\Cloud\Logging\LoggingClient;

ging = new LoggingClient([
'projectId' => 'my_project'


et a logger instance.
ger = $logging->logger('my_log');

rite a log entry.
ger->write('my message');

ist log entries from a specific log.
ries = $logging->entries([
'filter' => 'logName = projects/my_project/logs/my_log'


ach ($entries as $entry) {
echo $entry->info()['textPayload'] . "\n";

google/cloud-logging

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

mposer require google/cloud-logging
Cloud Firestore (Beta)
Preview
ire 'vendor/autoload.php';

Google\Cloud\Firestore\FirestoreClient;

estore = new FirestoreClient([
'projectId' => 'my_project'


lectionReference = $firestore->collection('Users');
umentReference = $collectionReference->document($userId);
pshot = $documentReference->snapshot();

 "Hello " . $snapshot['firstName'];
google/cloud-firestore

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

mposer require google/cloud-firestore
Google Cloud Container (Beta)
p
ire 'vendor/autoload.php';

Google\Cloud\Container\V1\ClusterManagerClient;

sterManagerClient = new ClusterManagerClient();

jectId = '[MY-PROJECT-ID]';
e = 'us-central1-a';

{
$clusters = $clusterManagerClient->listClusters($projectId, $zone);
foreach ($clusters->getClusters() as $cluster) {
    print('Cluster: ' . $cluster->getName() . PHP_EOL);
}
nally {
$clusterManagerClient->close();

google/cloud-container

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

mposer require google/cloud-container
Google Cloud Dataproc (Beta)
p
ire 'vendor/autoload.php';

Google\Cloud\Dataproc\V1\JobControllerClient;
Google\Cloud\Dataproc\V1\Job;
Google\Cloud\Dataproc\V1\HadoopJob;
Google\Cloud\Dataproc\V1\JobPlacement;

jectId = '[MY_PROJECT_ID]';
ion = 'global';
sterName = '[MY_CLUSTER]';

Placement = new JobPlacement();
Placement->setClusterName($clusterName);

oopJob = new HadoopJob();
oopJob->setMainJarFileUri('gs://my-bucket/my-hadoop-job.jar');

 = new Job();
->setPlacement($jobPlacement);
->setHadoopJob($hadoopJob);

ControllerClient = new JobControllerClient();
mittedJob = $jobControllerClient->submitJob($projectId, $region, $job);
google/cloud-dataproc

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

mposer require google/cloud-dataproc
Google Cloud Natural Language (Beta)
Preview
ire 'vendor/autoload.php';

Google\Cloud\Language\LanguageClient;

guage = new LanguageClient([
'projectId' => 'my_project'


nalyze a sentence.
otation = $language->annotateText('Greetings from Michigan!');

heck the sentiment.
$annotation->sentiment() > 0) {
echo "This is a positive message.\n";


etect entities.
ities = $annotation->entitiesByType('LOCATION');

ach ($entities as $entity) {
echo $entity['name'] . "\n";


arse the syntax.
ens = $annotation->tokensByTag('NOUN');

ach ($tokens as $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:

mposer require google/cloud-language
Google Cloud OsLogin (Beta)
p
ire 'vendor/autoload.php';

Google\Cloud\OsLogin\V1beta\OsLoginServiceClient;

oginServiceClient = new OsLoginServiceClient();
rId = '[MY_USER_ID]';
mattedName = $osLoginServiceClient->userName($userId);
inProfile = $osLoginServiceClient->getLoginProfile($formattedName);
google/cloud-oslogin

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

mposer require google/cloud-oslogin
Google Cloud Video Intelligence (Beta)
Preview
ire __DIR__ . '/vendor/autoload.php';

Google\Cloud\VideoIntelligence\V1\VideoIntelligenceServiceClient;
Google\Cloud\VideoIntelligence\V1\Feature;

eoIntelligenceServiceClient = new VideoIntelligenceServiceClient();

utUri = "gs://example-bucket/example-video.mp4";
tures = [
Feature::LABEL_DETECTION,

rationResponse = $videoIntelligenceServiceClient->annotateVideo($inputUri, $features);
rationResponse->pollUntilComplete();
$operationResponse->operationSucceeded()) {
$results = $operationResponse->getResult();
foreach ($results->getAnnotationResultsList() as $result) {
    foreach ($result->getLabelAnnotationsList() as $labelAnnotation) {
        echo "Label: " . $labelAnnotation->getDescription() . "\n";
    }
}
se {
$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:

mposer require google/cloud-videointelligence
Google Cloud Vision (Beta)
Preview
ire 'vendor/autoload.php';

Google\Cloud\Vision\VisionClient;

ion = new VisionClient([
'projectId' => 'my_project'


nnotate an image, detecting faces.
ge = $vision->image(
fopen('/data/family_photo.jpg', 'r'),
['faces']


otation = $vision->annotate($image);

etermine if the detected faces have headwear.
ach ($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:

mposer require google/cloud-vision
Google DLP (Beta)
Preview
ire 'vendor/autoload.php';

Google\Cloud\Dlp\V2\DlpServiceClient;
Google\Cloud\Dlp\V2\ContentItem;
Google\Cloud\Dlp\V2\InfoType;
Google\Cloud\Dlp\V2\InspectConfig;

ServiceClient = new DlpServiceClient();
oTypesElement = (new InfoType())
->setName('EMAIL_ADDRESS');
pectConfig = (new InspectConfig())
->setInfoTypes([$infoTypesElement]);
m = (new ContentItem())
->setValue('My email is example@example.com.');
mattedParent = $dlpServiceClient
->projectName('[PROJECT_ID]');

ponse = $dlpServiceClient->inspectContent($formattedParent, [
'inspectConfig' => $inspectConfig,
'item' => $item


dings = $response->getResult()
->getFindings();

ach ($findings as $finding) {
print $finding->getInfoType()
    ->getName() . PHP_EOL;

google/cloud-dlp

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

mposer require google/cloud-dlp
Google Stackdriver Error Reporting (Beta)
Preview
ire 'vendor/autoload.php';

Google\Cloud\ErrorReporting\V1beta1\ReportErrorsServiceClient;
Google\Cloud\ErrorReporting\\V1beta1\ReportedErrorEvent;

ortErrorsServiceClient = new ReportErrorsServiceClient();
mattedProjectName = $reportErrorsServiceClient->projectName('[PROJECT]');
nt = new ReportedErrorEvent();

{
$response = $reportErrorsServiceClient->reportErrorEvent($formattedProjectName, $event);
nally {
$reportErrorsServiceClient->close();

google/cloud-error-reporting

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

mposer require google/cloud-error-reporting
Google Stackdriver Monitoring (Beta)
Preview
ire 'vendor/autoload.php';

p

Google\Api\Metric;
Google\Api\MonitoredResource;
Google\Cloud\Monitoring\V3\MetricServiceClient;
Google\Cloud\Monitoring\V3\Point;
Google\Cloud\Monitoring\V3\TimeInterval;
Google\Cloud\Monitoring\V3\TimeSeries;
Google\Cloud\Monitoring\V3\TypedValue;
Google\Protobuf\Timestamp;

ricServiceClient = new MetricServiceClient();
mattedProjectName = $metricServiceClient->projectName($projectId);
els = [
'instance_id' => $instanceId,
'zone' => $zone,


 new Metric();
setType('custom.googleapis.com/my_metric');

 new MonitoredResource();
setType('gce_instance');
setLabels($labels);

ue = new TypedValue();
ue->setDoubleValue(3.14);

estamp = new Timestamp();
estamp->setSeconds(time());

erval = new TimeInterval();
erval->setStartTime($timestamp);
erval->setEndTime($timestamp);

nt = new Point();
nt->setValue($value);
nt->setInterval($interval);
nts = [$point];

eSeries = new TimeSeries();
eSeries->setMetric($m);
eSeries->setResource($r);
eSeries->setPoints($points);

{
$metricServiceClient->createTimeSeries($formattedProjectName, [$timeSeries]);
print('Successfully submitted a time series' . PHP_EOL);
nally {
$metricServiceClient->close();

google/cloud-monitoring

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

mposer require google/cloud-monitoring
Dialogflow API (Alpha)
Preview
ire 'vendor/autoload.php';

Google\Cloud\Dialogflow\V2\EntityTypesClient;

ityTypesClient = new EntityTypesClient();
jectId = '[MY_PROJECT_ID]';
ityTypeId = '[ENTITY_TYPE_ID]';
mattedEntityTypeName = $entityTypesClient->entityTypeName($projectId, $entityTypeId);

ityType = $entityTypesClient->getEntityType($formattedEntityTypeName);
ach ($entityType->getEntities() as $entity) {
print(PHP_EOL);
printf('Entity value: %s' . PHP_EOL, $entity->getValue());
print('Synonyms: ');
foreach ($entity->getSynonyms() as $synonym) {
    print($synonym . "\t");
}
print(PHP_EOL);

google/cloud-dialogflow

Dialogflow can be installed separately by requiring the google/cloud-dialogflow composer package:

mposer require google/cloud-dialogflow
Google Bigtable (Alpha)
Preview
ire 'vendor/autoload.php';

Google\Cloud\Bigtable\V2\BigtableClient;

tableClient = new BigtableClient();
mattedTableName = $bigtableClient->tableName('[PROJECT]', '[INSTANCE]', '[TABLE]');

{
$stream = $bigtableClient->readRows($formattedTableName);
foreach ($stream->readAll() as $element) {
    // doSomethingWith($element);
}
nally {
$bigtableClient->close();

google/cloud-bigtable

Google Bigtable can be installed separately by requiring the google/cloud-bigtable composer package:

mposer require google/cloud-bigtable
Google Cloud BigQuery Data Transfer (Alpha)
Preview
ire 'vendor/autoload.php';

Google\Cloud\BigQuery\DataTransfer\V1\DataTransferServiceClient;

aTransferServiceClient = new DataTransferServiceClient();
jectId = '[MY_PROJECT_ID]';
ation = 'us-central1';
mattedLocation = $dataTransferServiceClient->locationName($projectId, $location);
aSources = $dataTransferServiceClient->listDataSources($formattedLocation);
google/cloud-bigquerydatatransfer

Google Cloud BigQuery Data Transfer can be installed separately by requiring the google/cloud-bigquerydatatransfer composer package:

mposer require google/cloud-bigquerydatatransfer
Google Cloud IoT (Alpha)
Preview
ire 'vendor/autoload.php';

Google\Cloud\Iot\V1\DeviceManagerClient;

iceManager = new DeviceManagerClient();

jectId = '[MY_PROJECT_ID]';
ation = 'us-central1';
istryId = '[MY_REGISTRY_ID]';
istryName = $deviceManager->registryName($projectId, $location, $registryId);
ices = $deviceManager->listDevices($registryName);
ach ($devices->iterateAllElements() as $device) {
printf('Device: %s : %s' . PHP_EOL,
    $device->getNumId(),
    $device->getId()
);

google/cloud-iot

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

mposer require google/cloud-iot
Google Cloud Redis (Alpha)
Preview
ire 'vendor/autoload.php';

Google\Cloud\Redis\V1beta1\CloudRedisClient;

ent = new CloudRedisClient();

jectId = '[MY_PROJECT_ID]';
ation = '-'; // The '-' wildcard refers to all regions available to the project for the listInstances method
mattedLocationName = $client->locationName($projectId, $location);
ponse = $client->listInstances($formattedLocationName);
ach ($response->iterateAllElements() as $instance) {
printf('Instance: %s : %s' . PHP_EOL,
    $device->getDisplayName(),
    $device->getName()
);

google/cloud-redis

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

mposer require google/cloud-redis
Google Cloud Speech (Alpha)
Preview
ire 'vendor/autoload.php';

Google\Cloud\Speech\SpeechClient;

ech = new SpeechClient([
'projectId' => 'my_project',
'languageCode' => 'en-US'


ecognize the speech in an audio file.
ults = $speech->recognize(
fopen(__DIR__ . '/audio_sample.flac', 'r')


ach ($results as $result) {
echo $result->topAlternative()['transcript'] . "\n";

google/cloud-speech

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

mposer require google/cloud-speech
Google Stackdriver Debugger (Alpha)
Preview
Google\Cloud\Debugger\DebuggerClient;

ugger = new DebuggerClient();
uggee = $debugger->debugee();
uggee->register();
google/cloud-debugger

Stackdriver Debugger can be installed separately by requiring the google/cloud-debugger composer package:

mposer require google/cloud-debugger
Google Stackdriver Trace (Alpha)
Preview
ire 'vendor/autoload.php';

Google\Cloud\Trace\TraceClient;

ceClient = new TraceClient([
'projectId' => 'my_project'


reate a Trace
ce = $traceClient->trace();
n = $trace->span([
'name' => 'main'

n->setStart();
n->setEnd();

ce->setSpans([$span]);
ceClient->insert($trace);

ist recent Traces
ach($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:

mposer 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.

ire 'vendor/autoload.php';

Google\Cloud\Storage\StorageClient;
Symfony\Component\Cache\Adapter\ArrayAdapter;

lease take the proper precautions when storing your access tokens in a cache no matter the implementation.
he = new ArrayAdapter();

rage = new StorageClient([
'authCache' => $cache

This library provides a PSR-6 implementation with the SystemV shared memory at Google\Auth\Cache\SysVCacheItemPool. This implementation is only available on *nix machines, but it's the one of the fastest implementations and you can share the cache among multiple processes. The following example shows how to use it.

ire __DIR__ . '/vendor/autoload.php';

Google\Cloud\Spanner\SpannerClient;
Google\Auth\Cache\SysVCacheItemPool;

he = new SysVCacheItemPool();

nner = new SpannerClient([
'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.


This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.