首先,使用Composer(依赖管理器)安装官方的 Google Cloud Datastore PHP API。您可以通过将 "google/cloud-datastore": "^1.0" 添加到 composer.json 的“require”部分并运行 composer update
来做到这一点
您可以使用以下命令启动本地 Datastore 模拟器:
gcloud beta emulators datastore start
这是我编写的一个帮助程序类,用于处理与数据存储的连接:
<?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;
}
}
这是您将如何使用它将新实体插入数据存储区的方法
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);
如果您在使用模拟器时遇到问题,请尝试将您的代码部署到 App Engine 并查看是否有同样的错误。本地开发环境可能不稳定。
另外,请查看official PHP Datastore API docs here。