First install the official Google Cloud Datastore PHP API using Composer (dependency manager). You can do this by adding "google/cloud-datastore": "^1.0" to the "require" section of your composer.json and running composer update
You can start the local data warehouse emulator with the command:
gcloud beta emulators datastore start
Here the helper class wrote that the pens are connected to the data store:
<?php // Datastore.php use Google\Cloud\Datastore\DatastoreClient; class Datastore { private static $ds; /** * Creates or returns the Datastore instance * * @return void */ public static function getOrCreate() { if (isset(Datastore::$ds)) return Datastore::$ds; // gcloud beta emulators datastore start --data-dir=_datastore if (Datastore::isDevEnv() == true) { putenv('DATASTORE_EMULATOR_HOST=http://localhost:8081'); // To run locally, you may still need to download a credentials file from console.cloud.google.com //putenv('GOOGLE_APPLICATION_CREDENTIALS=' . __DIR__ . '/datastore_creds.json'); } $datastore = new DatastoreClient([ 'projectId' => Core::getProjectId() // 'keyFilePath' => 'datastore_creds.json' ]); Datastore::$ds = $datastore; return Datastore::$ds; } /** * Returns true if server running in development environment. * * @return boolean */ static function isDevEnv() { if (isset(Core::$_isDevEnv)) return Core::$_isDevEnv; Core::$_isDevEnv = (strpos(getenv('SERVER_SOFTWARE'), 'Development') === 0); return Core::$_isDevEnv; } /** * Formats fields and indexes for datastore. * @param Datastore $ds * @param Key $entityKey Datastore key. * @param [] $fields * @param [string] $indexes Keys to index. * @return Entity */ static function entityWithIndexes(DatastoreClient $ds, $entityKey, $fields, $indexes = []) { // Create exclude from indexes array. $excludedIndexes = []; foreach ($fields as $key => $value) { if (in_array($key, $indexes) == false) { $excludedIndexes[] = $key; } } $entity = $ds->entity($entityKey, $fields, [ 'excludeFromIndexes' => $excludedIndexes ]); return $entity; } }
Here you can use it to insert a new object into the data warehouse
require 'vendor/autoload.php'; require 'Datastore.php'; $ds = Datastore::getOrCreate(); $key = $ds->key('MyEntityType'); $data = [ 'name' => 'Foo!' ]; $indexes = ['name']; $entity = Datastore::entityWithIndexes($ds, $key, $data, $indexes); $ds->insert($entity);
If you have problems with the emulator, try deploying your code in the App Engine and see if you have the same error. The local development environment may be uneven.
Also, check out the official Datastore PHP API docs here .
Cal s source share