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.

如需了解详情,请参阅 Set up authentication for a local development environment

运行示例

该代码示例使用 PHP 版 Google Cloud 客户端库适用于 Cloud Bigtable 的 PHP 客户端库软件包与 Bigtable 通信。

要运行此示例程序,请按照 GitHub 上的相应示例说明执行操作。

将 Cloud 客户端库与 Bigtable 搭配使用

示例应用会连接到 Bigtable 并演示一些基本操作。

需要客户端库

该示例使用 ApiCore 的 ApiException 类,以及 PHP 版 Bigtable 客户端中的多个类。

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 对象。该表有一个列族,其中保留了每个列值的一个版本。

$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() 方法并传入过滤条件,以获取该行中每个列的一个版本。

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 仅会返回每个值的一个版本。

$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;
    }
}