I am using Google app engine for my web app and I need to use a NoSQL database, so my best option is Google Cloud Datastore
Since I can\'t find a way to connect it w
First, install the official Google Cloud Datastore PHP API using Composer (a 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 Datastore emulator with the command:
gcloud beta emulators datastore start
Here's a helper class I wrote that handles connecting to the datastore:
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's how you would use it to insert a new entity into the datastore
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 run into issues with the emulator, try deploying your code to App Engine and seeing if you have the same error. The local development environment can be flaky.
Also, check out the official PHP Datastore API docs here.