PHP の Hello World

このコードサンプルは、PHP で動作する「Hello World」アプリケーションです。このサンプルでは、次のタスクを行う方法を説明します。

  • 認証を設定する
  • Bigtable インスタンスに接続する
  • 新しいテーブルを作成する
  • テーブルにデータを書き込む
  • そのデータを読み取る
  • テーブルを削除する

認証を設定する

ローカル開発環境でこのページの Python サンプルを使用するには、gcloud CLI をインストールして初期化し、ユーザー認証情報を使用してアプリケーションのデフォルト認証情報を設定します。

  1. Install the Google Cloud CLI.
  2. To initialize the gcloud CLI, run the following command:

    gcloud init
  3. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

詳細については Set up authentication for a local development environment をご覧ください。

サンプルの実行

このコードサンプルでは、PHP 用 Google Cloud クライアント ライブラリCloud Bigtable 用 PHP クライアント ライブラリ パッケージを使用して Bigtable と通信します。

このサンプル プログラムを実行するには、GitHub でのサンプルの手順に沿って操作してください。

Bigtable での Cloud クライアント ライブラリの使用

このサンプル アプリケーションは Bigtable に接続して、いくつかのシンプルなオペレーションを行います。

必要なクライアント ライブラリ

このサンプルでは、ApiCore の ApiException クラスBigtable 用 PHP クライアントのクラス数を使用します。

use Google\ApiCore\ApiException;
use Google\Cloud\Bigtable\Admin\V2\Client\BigtableInstanceAdminClient;
use Google\Cloud\Bigtable\Admin\V2\Client\BigtableTableAdminClient;
use Google\Cloud\Bigtable\Admin\V2\ColumnFamily;
use Google\Cloud\Bigtable\Admin\V2\CreateTableRequest;
use Google\Cloud\Bigtable\Admin\V2\DeleteTableRequest;
use Google\Cloud\Bigtable\Admin\V2\GetTableRequest;
use Google\Cloud\Bigtable\Admin\V2\ModifyColumnFamiliesRequest;
use Google\Cloud\Bigtable\Admin\V2\ModifyColumnFamiliesRequest\Modification;
use Google\Cloud\Bigtable\Admin\V2\Table;
use Google\Cloud\Bigtable\Admin\V2\Table\View;
use Google\Cloud\Bigtable\BigtableClient;
use Google\Cloud\Bigtable\Mutations;
use Google\Cloud\Bigtable\V2\RowFilter;

Bigtable への接続

有効なGoogle Cloud プロジェクト ID、Bigtable インスタンス ID、テーブル ID を使用して、アプリケーションで使用する変数を設定します。次に、Bigtable への接続に使用する新しい BigtableInstanceAdminClientBigtableTableAdminClientBigtableClient オブジェクトをインスタンス化します。

/** Uncomment and populate these variables in your code */
// $projectId = 'The Google project ID';
// $instanceId = 'The Bigtable instance ID';
// $tableId = 'The Bigtable table ID';

$instanceAdminClient = new BigtableInstanceAdminClient();
$tableAdminClient = new BigtableTableAdminClient();
$dataClient = new BigtableClient([
    'projectId' => $projectId,
]);

テーブルの作成

テーブルがすでに存在するかどうかを確認します。存在しない場合は、createtable() メソッドを呼び出して Table オブジェクトを作成します。このテーブルには、各列の値の 1 つのバージョンを保持する単一の列ファミリーがあります。

$instanceName = $instanceAdminClient->instanceName($projectId, $instanceId);
$tableName = $tableAdminClient->tableName($projectId, $instanceId, $tableId);

// Check whether table exists in an instance.
// Create table if it does not exists.
$table = new Table();
printf('Creating a Table: %s' . PHP_EOL, $tableId);

try {
    $getTableRequest = (new GetTableRequest())
        ->setName($tableName)
        ->setView(View::NAME_ONLY);
    $tableAdminClient->getTable($getTableRequest);
    printf('Table %s already exists' . PHP_EOL, $tableId);
} catch (ApiException $e) {
    if ($e->getStatus() === 'NOT_FOUND') {
        printf('Creating the %s table' . PHP_EOL, $tableId);
        $createTableRequest = (new CreateTableRequest())
            ->setParent($instanceName)
            ->setTableId($tableId)
            ->setTable($table);

        $tableAdminClient->createtable($createTableRequest);
        $columnFamily = new ColumnFamily();
        $columnModification = new Modification();
        $columnModification->setId('cf1');
        $columnModification->setCreate($columnFamily);
        $modifyColumnFamiliesRequest = (new ModifyColumnFamiliesRequest())
            ->setName($tableName)
            ->setModifications([$columnModification]);
        $tableAdminClient->modifyColumnFamilies($modifyColumnFamiliesRequest);
        printf('Created table %s' . PHP_EOL, $tableId);
    } else {
        throw $e;
    }
}

テーブルへの行の書き込み

次に、グリーティングの文字列配列を使用してテーブルの新しい行を作成します。グリーティングごとに新しい Mutations オブジェクトを作成し、upsert() を使用して entries に追加します。次に、テーブルの mutateRows() メソッドを使用してテーブルにエントリを書き込みます。

$table = $dataClient->table($instanceId, $tableId);

printf('Writing some greetings to the table.' . PHP_EOL);
$greetings = ['Hello World!', 'Hello Cloud Bigtable!', 'Hello PHP!'];
$entries = [];
$columnFamilyId = 'cf1';
$column = 'greeting';
foreach ($greetings as $i => $value) {
    $rowKey = sprintf('greeting%s', $i);
    $rowMutation = new Mutations();
    $rowMutation->upsert($columnFamilyId, $column, $value, time() * 1000 * 1000);
    $entries[$rowKey] = $rowMutation;
}
$table->mutateRows($entries);

フィルタを使用した行の読み取り

書き込んだデータを読み取る前に、Bigtable によって返されるデータを制限するためのフィルタを作成します。このフィルタは、ガベージ コレクションが行われていない古いバージョンがテーブルに含まれていても、各値の最新バージョンのみを返すように Bigtable に指示します。

行オブジェクトを作成します。その後、readRow() メソッドを呼び出してフィルタを渡し、その行の各列の 1 つのバージョンを取得します。

printf('Getting a single greeting by row key.' . PHP_EOL);
$key = 'greeting0';
// Only retrieve the most recent version of the cell.
$rowFilter = (new RowFilter())->setCellsPerColumnLimitFilter(1);

$column = 'greeting';
$columnFamilyId = 'cf1';

$row = $table->readRow($key, [
    'filter' => $rowFilter
]);
printf('%s' . PHP_EOL, $row[$columnFamilyId][$column][0]['value']);

すべてのテーブル行のスキャン

テーブル内のすべての行を取得するには、readRows() メソッドを呼び出してフィルタを渡します。フィルタを渡しているため、Bigtable は各値の 1 つのバージョンのみを返します。

$columnFamilyId = 'cf1';
$column = 'greeting';
printf('Scanning for all greetings:' . PHP_EOL);
$partialRows = $table->readRows([])->readAll();
foreach ($partialRows as $row) {
    printf('%s' . PHP_EOL, $row[$columnFamilyId][$column][0]['value']);
}

テーブルの削除

管理クライアントの deleteTable() メソッドを使用してテーブルを削除します。

try {
    printf('Attempting to delete table %s.' . PHP_EOL, $tableId);
    $deleteTableRequest = (new DeleteTableRequest())
        ->setName($tableName);
    $tableAdminClient->deleteTable($deleteTableRequest);
    printf('Deleted %s table.' . PHP_EOL, $tableId);
} catch (ApiException $e) {
    if ($e->getStatus() === 'NOT_FOUND') {
        printf('Table %s does not exists' . PHP_EOL, $tableId);
    } else {
        throw $e;
    }
}

すべてを組み合わせる

コメントなしの完全なコードサンプルを以下に示します。

<?php



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

if (count($argv) != 4) {
    return printf('Usage: php %s PROJECT_ID INSTANCE_ID TABLE_ID' . PHP_EOL, __FILE__);
}
list($_, $projectId, $instanceId, $tableId) = $argv;

use Google\ApiCore\ApiException;
use Google\Cloud\Bigtable\Admin\V2\Client\BigtableInstanceAdminClient;
use Google\Cloud\Bigtable\Admin\V2\Client\BigtableTableAdminClient;
use Google\Cloud\Bigtable\Admin\V2\ColumnFamily;
use Google\Cloud\Bigtable\Admin\V2\CreateTableRequest;
use Google\Cloud\Bigtable\Admin\V2\DeleteTableRequest;
use Google\Cloud\Bigtable\Admin\V2\GetTableRequest;
use Google\Cloud\Bigtable\Admin\V2\ModifyColumnFamiliesRequest;
use Google\Cloud\Bigtable\Admin\V2\ModifyColumnFamiliesRequest\Modification;
use Google\Cloud\Bigtable\Admin\V2\Table;
use Google\Cloud\Bigtable\Admin\V2\Table\View;
use Google\Cloud\Bigtable\BigtableClient;
use Google\Cloud\Bigtable\Mutations;
use Google\Cloud\Bigtable\V2\RowFilter;



$instanceAdminClient = new BigtableInstanceAdminClient();
$tableAdminClient = new BigtableTableAdminClient();
$dataClient = new BigtableClient([
    'projectId' => $projectId,
]);

$instanceName = $instanceAdminClient->instanceName($projectId, $instanceId);
$tableName = $tableAdminClient->tableName($projectId, $instanceId, $tableId);

$table = new Table();
printf('Creating a Table: %s' . PHP_EOL, $tableId);

try {
    $getTableRequest = (new GetTableRequest())
        ->setName($tableName)
        ->setView(View::NAME_ONLY);
    $tableAdminClient->getTable($getTableRequest);
    printf('Table %s already exists' . PHP_EOL, $tableId);
} catch (ApiException $e) {
    if ($e->getStatus() === 'NOT_FOUND') {
        printf('Creating the %s table' . PHP_EOL, $tableId);
        $createTableRequest = (new CreateTableRequest())
            ->setParent($instanceName)
            ->setTableId($tableId)
            ->setTable($table);

        $tableAdminClient->createtable($createTableRequest);
        $columnFamily = new ColumnFamily();
        $columnModification = new Modification();
        $columnModification->setId('cf1');
        $columnModification->setCreate($columnFamily);
        $modifyColumnFamiliesRequest = (new ModifyColumnFamiliesRequest())
            ->setName($tableName)
            ->setModifications([$columnModification]);
        $tableAdminClient->modifyColumnFamilies($modifyColumnFamiliesRequest);
        printf('Created table %s' . PHP_EOL, $tableId);
    } else {
        throw $e;
    }
}

$table = $dataClient->table($instanceId, $tableId);

printf('Writing some greetings to the table.' . PHP_EOL);
$greetings = ['Hello World!', 'Hello Cloud Bigtable!', 'Hello PHP!'];
$entries = [];
$columnFamilyId = 'cf1';
$column = 'greeting';
foreach ($greetings as $i => $value) {
    $rowKey = sprintf('greeting%s', $i);
    $rowMutation = new Mutations();
    $rowMutation->upsert($columnFamilyId, $column, $value, time() * 1000 * 1000);
    $entries[$rowKey] = $rowMutation;
}
$table->mutateRows($entries);

printf('Getting a single greeting by row key.' . PHP_EOL);
$key = 'greeting0';
$rowFilter = (new RowFilter())->setCellsPerColumnLimitFilter(1);

$column = 'greeting';
$columnFamilyId = 'cf1';

$row = $table->readRow($key, [
    'filter' => $rowFilter
]);
printf('%s' . PHP_EOL, $row[$columnFamilyId][$column][0]['value']);

$columnFamilyId = 'cf1';
$column = 'greeting';
printf('Scanning for all greetings:' . PHP_EOL);
$partialRows = $table->readRows([])->readAll();
foreach ($partialRows as $row) {
    printf('%s' . PHP_EOL, $row[$columnFamilyId][$column][0]['value']);
}

try {
    printf('Attempting to delete table %s.' . PHP_EOL, $tableId);
    $deleteTableRequest = (new DeleteTableRequest())
        ->setName($tableName);
    $tableAdminClient->deleteTable($deleteTableRequest);
    printf('Deleted %s table.' . PHP_EOL, $tableId);
} catch (ApiException $e) {
    if ($e->getStatus() === 'NOT_FOUND') {
        printf('Table %s does not exists' . PHP_EOL, $tableId);
    } else {
        throw $e;
    }
}