簡單的控制檯應用

Git 專案站點下載 Apache Cassandra 的 Datastax PHP 驅動程式,並按照安裝說明進行操作。

我們將使用 KillrVideo 應用程式和 Datastax PHP 驅動程式中的 使用者 表。啟動並執行 Cassandra 後,建立以下鍵空間和表: ****

//Create the keyspace
    CREATE KEYSPACE killrvideo WITH REPLICATION = 
    { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };

//Use the keyspace
USE killrvideo;

// Users keyed by id
CREATE TABLE users (
    userid uuid,
    firstname text,
    lastname text,
    email text,
    created_date timestamp,
    PRIMARY KEY (userid)
);

使用你喜歡的編輯器建立一個 PHP 檔案。首先,我們需要連線到我們的 killrvideo 鍵空間和叢集:

build();
$keyspace  = 'killrvideo';
$session  = $cluster->connect($keyspace);

讓我們將使用者插入 users 表:

execute(new Cassandra\SimpleStatement(
    "INSERT INTO users (userid, created_date, email, firstname, lastname) 
      VALUES (14c532ac-f5ae-479a-9d0a-36604732e01d, '2013-01-01 00:00:00', 
      'luke@example.com','Luke','Tillman')"
  ));

使用 Datastax PHP Cassandra 驅動程式,我們可以通過 userid 查詢使用者:

execute(new Cassandra\SimpleStatement
          ("SELECT firstname, lastname, email FROM killrvideo.users
            WHERE userid=14c532ac-f5ae-479a-9d0a-36604732e01d"));

foreach ($result as $row) {
    printf("user: \"%s\" \"%s\" email: \"%s\" \n", $row['firstname'],
    $row['lastname'], $row['email']);
  }

要讓使用者更新系統中的電子郵件地址:

execute(new Cassandra\SimpleStatement
          ("UPDATE users SET email = 'language_evangelist@example.com' 
            WHERE userid = 14c532ac-f5ae-479a-9d0a-36604732e01d"));

execute(new Cassandra\SimpleStatement
          ("SELECT firstname, lastname, email FROM killrvideo.users 
            WHERE userid=14c532ac-f5ae-479a-9d0a-36604732e01d"));

foreach ($result as $row) {
    printf("user: \"%s\" \"%s\" email: \"%s\" \n", $row['firstname'], 
    $row['lastname'], $row['email']);
  }

從表中刪除使用者並輸出所有行。你會注意到使用者的資訊在刪除後不再返回:

execute(new Cassandra\SimpleStatement
          ("DELETE FROM users WHERE userid = 14c532ac-f5ae-479a-9d0a-36604732e01d"));

execute(new Cassandra\SimpleStatement
          ("SELECT firstname, lastname, email FROM killrvideo.users 
            WHERE userid=14c532ac-f5ae-479a-9d0a-36604732e01d"));

foreach ($result as $row) {
    printf("user: \"%s\" \"%s\" email: \"%s\" \n", $row['firstname'], 
    $row['lastname'], $row['email']);
  }

輸出應該如下所示:

user: "Luke" "Tillman" email: "luke@example.com" 
user: "Luke" "Tillman" email: "language_evangelist@example.com"

參考文獻

Apache Cassandra 和 PHP 入門 ,DataStax Academy