Using Cloud Datastore

You can use Google Cloud Datastore to store application data from your App Engine app. Cloud Datastore is a database built for automatic scaling, high performance, and ease of application development.

This document describes how to use the Google Cloud Client Library to store and retrieve data using Cloud Datastore in an App Engine app.

Prerequisites and setup

Follow the instructions in "Hello, World!" for PHP on App Engine to set up your environment and project, and to understand how PHP apps are structured in App Engine. Write down and save your project ID, because you will need it to run the sample application described in this document.

Clone the repository

Download (clone) the sample:

git clone https://github.com/GoogleCloudPlatform/php-docs-samples
cd php-docs-samples/appengine/flexible/datastore

Edit project configuration and set dependencies

Install dependencies using Composer:

composer install

Application code

The sample application logs, retrieves, and displays visitor IPs.

The application first instantiates a Cloud Datastore client:

$datastore = new DatastoreClient([
    'projectId' => $projectId
]);

Each visit is an entity with fields for the visitor's IP address and a timestamp, and is saved to Cloud Datastore using the insert command:

// Create an entity to insert into datastore.
$key = $datastore->key('visit');
$entity = $datastore->entity($key, [
    'user_ip' => $user_ip,
    'timestamp' => new DateTime(),
]);
$datastore->insert($entity);

The ten most recent visits are retrieved in descending order using the query command:

// Query recent visits.
$query = $datastore->query()
    ->kind('visit')
    ->order('timestamp', 'DESCENDING')
    ->limit(10);
$results = $datastore->runQuery($query);
$visits = [];
foreach ($results as $entity) {
    $visits[] = sprintf('Time: %s Addr: %s',
        $entity['timestamp']->format('Y-m-d H:i:s'),
        $entity['user_ip']);
}

Using index.yaml files

The sample app performs simple queries. More elaborate Datastore queries require one or more indexes, which you must specify in an index.yaml file that you upload along with your app. This file may be created manually, or generated automatically while testing your app locally.

For more information

For complete information on Cloud Datastore, including optimizations and concepts, see the Cloud Datastore documentation.

Monitor your resources on the go

Get the Google Cloud Console app to help you manage your projects.

Send feedback about...

App Engine flexible environment for PHP docs