简单的控制台应用

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