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. Create local authentication credentials for your user account:

    gcloud auth application-default login

자세한 내용은 다음을 참조하세요: Set up authentication for a local development environment.

샘플 실행

이 코드 샘플은 PHP용 Google Cloud 클라이언트 라이브러리Cloud Bigtable용 PHP 클라이언트 라이브러리를 사용하여 Bigtable과 통신합니다.

이 샘플 프로그램을 실행하려면 GitHub에서 샘플 안내를 따르세요.

Cloud 클라이언트 라이브러리를 Bigtable과 함께 사용

샘플 애플리케이션을 Bigtable에 연결하여 몇 가지 기본 작업을 보여줍니다.

클라이언트 라이브러리 필요

이 샘플은 Bigtable용 PHP 클라이언트에 있는 많은 클래스는 물론 ApiCore의 ApiException 클래스를 사용합니다.

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에 연결하는 데 사용할 새 BigtableInstanceAdminClient, BigtableTableAdminClient, BigtableClient 객체를 인스턴스화합니다.

/** 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 객체를 만듭니다. 테이블에는 각 열 값별로 버전 하나만 보관하는 column family가 한 개 있습니다.

$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은 각 값별로 버전 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;
    }
}