PHP is one of the most commonly used scripting languages, and its usage for developing websites continues to increase. PHP is an open source, object-oriented, server-side language and has the advantages of simplicity with support for all or most operating systems and Web servers. A few PHP clients for Cassandra are available, including phpcassa, which is a PHP client library for Apache Cassandra with support for PHP 5.3+. In this chapter, you will use phpcassa to access Cassandra and perform CRUD operations on Cassandra from PHP scripts.
Phpcassa provides several namespaces for a PHP client to access Apache Cassandra. A PHP namespace is an abstraction to encapsulate related, reusable code elements such as classes, interfaces, functions, and constants. The top-level namespace is phpcassa
. The main classes within the top level namespace are shown in Figure 4.1.
The main classes in the phpcassa
namespace are discussed in Table 4.1.
The top-level namespace phpcassa
has several sub-namespaces, which are outlined in Figure 4.2.
The sub-namespaces in the phpcassa
namespace are discussed in Table 4.2.
Each of the namespaces contains classes specific to the namespace. The main classes in the phpcassaBatch
namespace are shown in Figure 4.3.
The phpcassaBatch
namespace main classes are discussed in Table 4.3.
The phpcassaConnection
namespace provides the ConnectionPool
class and the exceptions in Figure 4.4.
The classes and exceptions in the phpcassaConnection
namespace are discussed in Table 4.4.
The phpcassaIndex
namespace provides the classes in Figure 4.5.
The classes in the phpcassaIndex
namespace are discussed in Table 4.5.
The classes in the phpcassaSchema
namespace are outlined in Figure 4.6.
The classes in the phpcassaSchema
namespace are discussed in Table 4.6.
The DataType
class provides various data types as string constants. Some of the main data types are listed in Figure 4.7.
Some of the main data types in the DataType
class are discussed in Table 4.7.
In addition to installing Apache Cassandra server, you must install the following software:
PHP
PHP client library for Cassandra
Then follow these steps:
1. Add the bin folder, C:Cassandraapache-cassandra-2.0.4in, to the PATH
environment variable.
2. Start the Cassandra server with the following command:
cassandra -f
PHP 5.4 and later versions include a Web server packaged in the PHP installation and do not require the Web server to be installed separately. To install PHP, follow these steps:
1. Download the latest version of the PHP TAR file from http://php.net/downloads.php.
2. Extract the TAR file to a directory (C:PHP is used in this chapter) with the following command:
tar -xzf php-5.4.23.tar.gz
3. Rename the php.ini-development or php.ini-production file in the root directory of the PHP installation (C:PHPphp-5.4.24-Win32-VC9-x86) to php.ini.
4. Connect to the packaged Web server with the following command from the C:PHPphp-5.4.24-Win32-VC9-x86 directory:
php -S localhost:8000
The output from the command indicates that the development server has been started and is listening on http://localhost:8000. (See Figure 4.8.)
The document root is the directory to which the TAR file is extracted, C:PHPphp-5.4.24-Win32-VC9-x86. Any PHP script phpscript.php copied to the document root directory may be run on the integrated Web server with the URL http://localhost:8000/phpscript.php. You can copy PHP scripts to a subdirectory of the document root directory and run them by including the directory path, starting from the document root, in the URL.
To install phpcassa, follow these steps:
1. Download the phpcassa library from https://github.com/thobbs/phpcassa. The Download ZIP downloads the phpcassa-master.zip file.
2. Extract the phpcassa-master.zip file to the C:PHPphp-5.4.24-Win32-VC9-x86 directory.
3. Create a subdirectory, scripts, in the phpcassa-master directory.
You will add PHP scripts to the phpcassa-masterscripts directory and run the scripts in the integrated Web server. The URL to run a script phpscript.php in the phpcassa-masterscripts directory is http://localhost:8000/phpcassa-master/scripts/phpscript.php.
A keyspace is the top-level namespace for storing data in a Cassandra database. First, you need to create a keyspace in Cassandra. Create a PHP script, createKeyspace.php, in the phpcassa-masterscripts directory. Include the phpcassa library in the PHP script with the following statement:
require_once(__DIR__.'/../lib/autoload.php'),
Import the ConnectionPool
, SystemManager
, and StrategyClass
classes using use
statements. Create a SystemManager
object using the following class constructor:
__construct( string $server = 'localhost:9160', array $credentials = NULL, integer $send_timeout = 15000, integer $recv_timeout = 15000 )
The constructor parameters are discussed in Table 4.8.
Create an instance of SystemManager
as follows.
$sys = new SystemManager('127.0.0.1'),
Create a keyspace using the create_keyspace($keyspace, $attrs)
method from the SystemManager
class. The $keyspace
parameter is the keyspace name and the $attrs
parameter is for the attributes of the keyspace. The attributes discussed in Table 4.9 are supported.
Create a keyspace using Simple_Strategy
and a replication_factor
of 1
:
$sys->create_keyspace('php_catalog', array( "strategy_class" => StrategyClass::SIMPLE_STRATEGY, "strategy_options" => array('replication_factor' => '1')));
The PHP script createKeyspace.php appears in Listing 4.1.
Listing 4.1 The createKeyspace.php Script
<?php require_once(__DIR__.'/../lib/autoload.php'), use phpcassaConnectionConnectionPool; use phpcassaSystemManager; use phpcassaSchemaStrategyClass; $sys = new SystemManager('127.0.0.1'), $sys->create_keyspace('php_catalog', array( "strategy_class" => StrategyClass::SIMPLE_STRATEGY, "strategy_options" => array('replication_factor' => '1'))); echo 'Keyspace php_catalog created'; ?>
With the Cassandra server running and the PHP integrated server started, invoke the PHP script with the URL http://localhost:8000/phpcassa-master/scripts/createKeyspace. php. The php_catalog
keyspace is created in Cassandra, as shown in Figure 4.9.
Log in to the Cassandra client with the cassandra-cli batch application. Then run the following command to use the newly created keyspace php_catalog
:
use php_catalog;
As indicated by the output in the Cassandra client, the php_catalog
keyspace is authenticated. (See Figure 4.10.)
Next, you will create a column family in Cassandra.
A column family or a table is the data structure to store data in Cassandra. To create a column family, first create a PHP script, createCF.php, in the phpcassa-masterscripts directory. Include the phpcassa library in the PHP script and import the ConnectionPool
, SystemManager
, and StrategyClass
classes as in the preceding section. Create a SystemManager
object using the class constructor, also as in the preceding section. The SystemManager
class provides the following method to create a column family:
create_column_family( string $keyspace, string $column_family, array $attrs = null )
The method parameters are discussed in Table 4.10.
Create a column family called catalog
in the php_catalog
keyspace using UTF8Type
for comparator_type
, key_validation_class
, and default_validation_class
.
$sys->create_column_family('php_catalog', 'catalog', array( "column_type" => "Standard", "comparator_type" => "UTF8Type", "key_validation_class" => "UTF8Type", "default_validation_class" => "UTF8Type" ));
Next, create a ConnectionPool
instance using the following class constructor:
__construct( string $keyspace, mixed $servers = NULL, integer $pool_size = NULL, integer $max_retries = phpcassaConnectionConnectionPool::DEFAULT_MAX_RETRIES, integer $send_timeout = 5000, integer $recv_timeout = 5000, integer $recycle = phpcassaConnectionConnectionPool::DEFAULT_RECYCLE, mixed $credentials = NULL, boolean $framed_transport = true )
The constructor supports the parameters discussed in Table 4.11.
Create a ConnectionPool
instance using the php_catalog
keyspace and the '127.0.0.1'
host.
$pool = new ConnectionPool('php_catalog', array('127.0.0.1'));
You created a column family earlier. Create a ColumnFamily
instance using the following class constructor:
_construct($pool, $column_family,$autopack_names=true, $autopack_values=true, $read_consistency_level=ConsistencyLevel::ONE,$write_consistency_level= ConsistencyLevel::ONE,$buffer_size=self::DEFAULT_BUFFER_SIZE)
The ColumnFamily
class constructors are discussed in Table 4.12.
Create a ColumnFamily
instance called catalog
using the ConnectionPool
instance created earlier and the catalog column family. Default values are used for the other attributes.
$catalog = new ColumnFamily($pool, 'catalog'),
The PHP script createCF.php appears in Listing 4.2.
Listing 4.2 The createCF.php Script
<?php require_once(__DIR__.'/../lib/autoload.php'), use phpcassaConnectionConnectionPool; use phpcassaColumnFamily; use phpcassaSystemManager; $sys = new SystemManager('127.0.0.1'), $sys->create_column_family('php_catalog', 'catalog', array( "column_type" => "Standard", "comparator_type" => "UTF8Type", "key_validation_class" => "UTF8Type", "default_validation_class" => "UTF8Type" )); $pool = new ConnectionPool('php_catalog', array('127.0.0.1')); $catalog = new ColumnFamily($pool, 'catalog'), echo 'column family catalog created'; ?>
With the Cassandra server running and the PHP integrated server started, invoke the PHP script with the URL http://localhost:8000/phpcassa-master/scripts/createCF.php. The catalog
column family is created in Cassandra. (See Figure 4.11.)
Next, you will add data to the column family created in this section.
Cassandra stores data in rows and columns in a column family. To see how this works, create a PHP script, add.php, in the phpcassa-masterscripts directory for adding data to Cassandra. Include the phpcassa library in the PHP script. Import the ConnectionPool
, SystemManager
, and StrategyClass
classes and create a SystemManager
object using the class constructor. The ColumnFamily
class provides the insert()
method to add data to columns in a row. The required parameters of the insert()
method are discussed in Table 4.13.
Create a ColumnFamily
instance as discussed in the previous section.
$pool = new ConnectionPool('php_catalog', array('127.0.0.1')); $catalog = new ColumnFamily($pool, 'catalog'),
Add two rows of data to rows identified by "catalog1"
and "catalog2"
. Then create an array of column name/value pairs for the journal
, publisher
, edition
, title
, and author
columns.
$catalog->insert('catalog1', array("journal" => "Oracle Magazine", "publisher" => "Oracle Publishing","edition" => "November-December 2013", "title" => "Quintessential and Collaborative","author" => "Tom Haunert")); $catalog->insert('catalog2', array("journal" => "Oracle Magazine", "publisher" => "Oracle Publishing","edition" => "November-December 2013", "title" => "Engineering as a Service","author" => "David A. Kelly"));
The PHP script add.php appears in Listing 4.3.
Listing 4.3 The add.php Script
<?php require_once(__DIR__.'/../lib/autoload.php'), use phpcassaConnectionConnectionPool; use phpcassaColumnFamily; use phpcassaSystemManager; $sys = new SystemManager('127.0.0.1'), $pool = new ConnectionPool('php_catalog', array('127.0.0.1')); $catalog = new ColumnFamily($pool, 'catalog'), $catalog->insert('catalog1', array("journal" => "Oracle Magazine", "publisher" => "Oracle Publishing","edition" => "November-December 2013", "title" => "Quintessential and Collaborative","author" => "Tom Haunert")); $catalog->insert('catalog2', array("journal" => "Oracle Magazine", "publisher" => "Oracle Publishing","edition" => "November-December 2013", "title" => "Engineering as a Service","author" => "David A. Kelly")); echo 'Catalog ids catalog1 and catalog2 added'; //$catalog->remove("catalog1"); //$catalog->remove("catalog2"); ?>
With the Cassandra server running and the PHP integrated server started, invoke the PHP script with the URL http://localhost:8000/phpcassa-master/scripts/add.php. Two rows of data are added to the column family catalog
. (See Figure 4.12.)
In this section, you added only a row of data. In the next section, you will add multiple rows in the same statement. A row of data may be removed with the remove($key)
method. If the same key identifiers are to be used for adding multiple rows, remove the rows added in this section by running the add.php script with the remove()
method invocations commented out.
In this section, you will add data to multiple rows in a batch. Create a PHP script, add_batch.php, in the phpcassa-masterscripts directory for adding data to Cassandra. Include the phpcassa library in the PHP script. Import the ConnectionPool
, SystemManager
, and StrategyClass
classes and create a SystemManager
object using the class constructor. The ColumnFamily
class provides the insert()
method to add data to columns in a row. The required parameters of the batch_insert
method are discussed in Table 4.14.
Add the catalog1
and catalog2
rows in a batch using the batch_insert
method as follows:
$catalog->batch_insert(array("catalog1" => array("journal" => "Oracle Magazine", "publisher" => "Oracle Publishing","edition" => "November-December 2013", "title" => "Quintessential and Collaborative","author" => "Tom Haunert"), "catalog2" => array("journal" => "Oracle Magazine", "publisher" => "Oracle Publishing","edition" => "November-December 2013", "title" => "Engineering as a Service","author" => "David A. Kelly")));
The ColumnFamily
class provides the multiget()
method to fetch multiple rows of data. The multiget()
method is discussed later in this chapter, in the section, “Getting Columns from Multiple Rows.” In this section, use the multiget()
method to fetch the rows added with the batch_insert
method.
$catalogs = $catalog->multiget(array('catalog1', 'catalog2'));
The multiget()
method returns mixed array(key => array(column_name => column_value))
. Iterate over the array to output individual columns.
foreach($catalogs as $catalog_id => $columns) { echo "Journal: ".$columns["journal"]." "; echo "Publisher: ".$columns["publisher"]." "; echo "Edition: ".$columns["edition"]." "; echo "Title: ".$columns["title"]." "; echo "Author: ".$columns["author"]." "; echo "<br> "; }
The add_batch.php
PHP script appears in Listing 4.4.
Listing 4.4 The add_batch.php Script
<?php require_once(__DIR__.'/../lib/autoload.php'), use phpcassaConnectionConnectionPool; use phpcassaColumnFamily; use phpcassaSystemManager; use phpcassaSchemaStrategyClass; $sys = new SystemManager('127.0.0.1'), $sys->create_keyspace('batch_catalog', array( "strategy_class" => StrategyClass::SIMPLE_STRATEGY, "strategy_options" => array('replication_factor' => '1'))); $sys->create_column_family('batch_catalog', 'catalog', array( "column_type" => "Standard", "comparator_type" => "UTF8Type", "key_validation_class" => "UTF8Type", "default_validation_class" => "UTF8Type" )); $pool = new ConnectionPool('batch_catalog', array('127.0.0.1')); $catalog = new ColumnFamily($pool, 'catalog'), $catalog->batch_insert(array("catalog1" => array("journal" => "Oracle Magazine", "publisher" => "Oracle Publishing","edition" => "November-December 2013", "title" => "Quintessential and Collaborative","author" => "Tom Haunert"), "catalog2" => array("journal" => "Oracle Magazine", "publisher" => "Oracle Publishing","edition" => "November-December 2013", "title" => "Engineering as a Service","author" => "David A. Kelly"))); echo 'Catalog ids catalog1 and catalog2 added as a batch '; echo "<br> "; $catalogs = $catalog->multiget(array('catalog1', 'catalog2')); foreach($catalogs as $catalog_id => $columns) { echo "Journal: ".$columns["journal"]." "; echo "Publisher: ".$columns["publisher"]." "; echo "Edition: ".$columns["edition"]." "; echo "Title: ".$columns["title"]." "; echo "Author: ".$columns["author"]." "; echo "<br> "; } $sys->drop_keyspace("batch_catalog"); $pool->close(); $sys->close(); ?>
With the Cassandra server running and the PHP integrated server started, invoke the PHP script with the URL http://localhost:8000/phpcassa-master/scripts/add_batch.php. Two rows of data are added to the column family catalog
, and are fetched and output. (See Figure 4.13.)
Having added data, you will next retrieve data from Cassandra.
In this section, you will retrieve data from Cassandra using phpcassa. Create a PHP script, get.php, in the phpcassa-masterscripts directory for getting data from Cassandra. As in other sections, include the phpcassa library in the PHP script. Import the ConnectionPool
, SystemManager
, and StrategyClass
classes, and create a SystemManager
object using the class constructor. The ColumnFamily
class provides the following method to get()
:
get($key,$column_slice=null,$column_names=null,$consistency_level=null)
The parameters of the get()
method are discussed in Table 4.15.
The get()
method returns mixed array(column_name => column_value)
. Get the array of columns for row key 'catalog1'
.
$catalog1= $catalog->get('catalog1'),
The following method returns the number of columns in a row:
get_count($key,$column_slice=null,$column_names=null,$consistency_level=null)
The parameters of the get_count()
method are discussed in Table 4.16.
The get_count()
method returns an int
value. Get the number of columns in the 'catalog1'
row.
echo $catalog->get_count('catalog1'),
Get the column values by dereferencing the array using column names. For example, the column value for the journal
column is output as follows:
echo $journal = $catalog1["journal"];
Similarly, get the array of columns in the 'catalog2'
row.
$catalog2= $catalog->get('catalog2'),
The get.php script appears in Listing 4.5.
Listing 4.5 The get.php Script
<?php require_once(__DIR__.'/../lib/autoload.php'), use phpcassaConnectionConnectionPool; use phpcassaColumnFamily; use phpcassaSystemManager; $sys = new SystemManager('127.0.0.1'), $pool = new ConnectionPool('php_catalog', array('127.0.0.1')); $catalog = new ColumnFamily($pool, 'catalog'), $catalog1= $catalog->get('catalog1'), echo "catalog1"; echo "<br> "; echo "Number of Columns in catalog1: "; echo $catalog->get_count('catalog1'), echo "<br> "; echo "Journal: "; echo $journal = $catalog1["journal"]; echo "<br> "; echo "Publisher: "; echo $publisher = $catalog1["publisher"]; echo "<br> "; echo "Edition: "; echo $edition = $catalog1["edition"]; echo "<br> "; echo "Title: "; echo $title = $catalog1["title"]; echo "<br> "; echo "Author: "; echo $author = $catalog1["author"]; echo "<br> "; echo "<br> "; $catalog2= $catalog->get('catalog2'), echo "catalog2"; echo "<br> "; echo "Number of Columns in catalog2: "; echo $catalog->get_count('catalog2'), echo "<br> "; echo "Journal: "; echo $journal = $catalog2["journal"]; echo "<br> "; echo "Publisher: "; echo $publisher = $catalog2["publisher"]; echo "<br> "; echo "Edition: "; echo $edition = $catalog2["edition"]; echo "<br> "; echo "Title: "; echo $title = $catalog2["title"]; echo "<br> "; echo "Author: "; echo $author = $catalog2["author"]; echo "<br> "; ?>
With the Cassandra server running and the PHP integrated server started, invoke the PHP script with the URL http://localhost:8000/phpcassa-master/scripts/get.php. The two rows of data are fetched individually and the column values are output. (See Figure 4.14.)
In this section, you fetched all the columns, but all columns don’t have to be fetched. In the next section, you will fetch only selected columns.
You will use the same method to fetch selected columns:
get_count($key,$column_slice=null,$column_names=null,$consistency_level=null)
Create a PHP script, get_columns.php, in the phpcassa-masterscripts directory for getting selected columns from Cassandra. Then invoke the get()
method with the row key as 'catalog1'
. For the $column_names
argument, specify three columns: journal
, title
, and author
.
$columns = $catalog->get('catalog1', $column_slice=null, $column_names=array ("journal", "title","author"));
Output the column values using the array dereferencing using the column name.
echo "Journal: ".$columns["journal"].", "; echo "Title: ".$columns["title"].", "; echo "Author: ".$columns["author"].", ";
The get_columns.php script appears in Listing 4.6.
Listing 4.6 The get_columns.php Script
<?php require_once(__DIR__.'/../lib/autoload.php'), use phpcassaConnectionConnectionPool; use phpcassaColumnFamily; use phpcassaSystemManager; $sys = new SystemManager('127.0.0.1'), $pool = new ConnectionPool('php_catalog', array('127.0.0.1')); $catalog = new ColumnFamily($pool, 'catalog'), $columns = $catalog->get('catalog1', $column_slice=null, $column_names=array ("journal", "title","author")); echo "Journal: ".$columns["journal"].", "; echo "Title: ".$columns["title"].", "; echo "Author: ".$columns["author"].", "; ?>
Invoke the PHP script with the URL http://localhost:8000/phpcassa-master/scripts/get_ columns.php. The three columns of data are fetched and column values are output. (See Figure 4.15.)
In the preceding two sections, you fetched a column from a single row. In the next section, you will fetch columns from multiple rows.
The ColumnFamily
class provides the following method to fetch columns from multiple rows:
multiget($keys,$column_slice=null,$column_names=null,$consistency_level=null, $buffer_size=16)
The parameters of the method are discussed in Table 4.17.
The multiget()
method returns mixed array(key => array(column_name => column_ value))
. Create a PHP script, get_multi.php, in the phpcassa-masterscripts directory for fetching multiple rows from Cassandra. Then invoke the multiget()
method with row arrays for 'catalog1'
and 'catalog2'
. For the $column_names
argument, specify three columns: journal
, title
, and author
. Iterate over the array returned by the method to output column values for the title
and author
columns.
foreach($catalogs as $catalog_id => $columns) { echo "Title: ".$columns["title"]." "; echo "Author: ".$columns["author"]." "; echo "<br> "; }
The ColumnFamily
class provides the following method to get the column count for multiple rows in the same statement:
multiget_count($keys,$column_slice=null,$column_names=null, $consistency_level=null)
The parameters for the multiget_count()
method are the same as for the multiget()
method except that the multiget_count()
method does not have $buffer_size
as a parameter. The method returns mixed array(row_key => row_count)
. Invoke the method for the 'catalog1'
and 'catalog2'
rows.
$array= $catalog->multiget_count(["catalog1", "catalog2"]);
Output the array returned using var_dump
:
var_dump($array);
The get_multi.php script appears in Listing 4.7.
Listing 4.7 The get_multi.php Script
<?php require_once(__DIR__.'/../lib/autoload.php'), use phpcassaConnectionConnectionPool; use phpcassaColumnFamily; use phpcassaSystemManager; $sys = new SystemManager('127.0.0.1'), $pool = new ConnectionPool('php_catalog', array('127.0.0.1')); $catalog = new ColumnFamily($pool, 'catalog'), $catalogs = $catalog->multiget(array('catalog1', 'catalog2')); foreach($catalogs as $catalog_id => $columns) { echo "Title: ".$columns["title"]." "; echo "Author: ".$columns["author"]." "; echo "<br> "; } echo "<br> "; echo "Column Count: "; $array= $catalog->multiget_count(["catalog1", "catalog2"]); var_dump($array); ?>
Invoke the PHP script with the URL http://localhost:8000/phpcassa-master/scripts/get_ multi.php. The two rows of data are fetched, and two columns of data are output. (See Figure 4.16.)
You did not use all of the parameters in the get()
method to fetch columns. Specifically, you did not use the $column_slice
parameter, which fetches only the specified slice of columns. Next, you will use the $column_slice
parameter to fetch a slice of columns. A slice of columns is represented with the phpcassaColumnSlice
class. The constructor for the ColumnSlice
class is as follows:
__construct ($start="", $finish="",$count=self::DEFAULT_COLUMN_COUNT, $reversed=False)
The constructor parameters are discussed in Table 4.18.
We will discuss ColumnSlice
with several examples. Create a PHP script, column_slices. php, in the phpcassa-masterscripts directory. Then get the columns, starting with the first column from 'catalog2'
row.
$slice = new ColumnSlice(1); var_dump($catalog->get('catalog2', $slice));
Next, get the column slice starting from the second column and ending with the fifth column from the 'catalog1'
row.
$slice = new ColumnSlice(2, 5); var_dump($catalog->get('catalog1', $slice));
To demonstrate the $count
parameter, get columns from the row 'catalog1'
. Although the start and finish are specified as ''
, which implies all columns are to be fetched, only three columns are fetched because the $count
is specified as 3
. Three columns are fetched starting from the first column.
$slice = new ColumnSlice('', '', $count=3); var_dump($catalog->get('catalog1', $slice));
Next, specify start and finish as ''
and specify $count
as 5
. Also set $reversed
to true
. Five columns starting from the end are fetched. Because the total number of columns is five, all columns get fetched.
$slice = new ColumnSlice('', '', $count=5, $reversed=true); var_dump($catalog->get('catalog1', $slice));
As another example, specify $start
as 3
and $finish
as ''
. Then specify $count
as 2
and set $reversed
to true
. Two columns, starting from the third column and moving toward the start of the row, are fetched.
$slice = new ColumnSlice(3, '', $count=2, $reversed=true); var_dump($catalog->get('catalog1', $slice));
Because the start and finish index are specified as numbers, the comparator_type
for the column family must be set to LongType
.
$sys->create_column_family('catalogks', 'catalog', array( "column_type" => "Standard", "comparator_type" => "LongType", "key_validation_class" => "UTF8Type", "default_validation_class" => "UTF8Type" ));
The column_slices.php script appears in Listing 4.8.
Listing 4.8 The column_slices.php Script
<?php require_once(__DIR__.'/../lib/autoload.php'), use phpcassaConnectionConnectionPool; use phpcassaColumnFamily; use phpcassaColumnSlice; use phpcassaSystemManager; use phpcassaSchemaStrategyClass; $sys = new SystemManager('127.0.0.1'), $sys->create_keyspace('catalogks', array( "strategy_class" => StrategyClass::SIMPLE_STRATEGY, "strategy_options" => array('replication_factor' => '1') )); $sys->create_column_family('catalogks', 'catalog', array( "column_type" => "Standard", "comparator_type" => "LongType", "key_validation_class" => "UTF8Type", "default_validation_class" => "UTF8Type" )); // Start a connection pool, create our ColumnFamily instance $pool = new ConnectionPool('catalogks', array('127.0.0.1')); $catalog = new ColumnFamily($pool, 'catalog'), $columns = array(1 => "Oracle Magazine", 2 => "Oracle Publishing", 3 => "November- December 2013", 4 => "Quintessential and Collaborative", 5 => "Tom Haunert"); $catalog->insert('catalog1', $columns); $columns = array(1 => "Oracle Magazine", 2 => "Oracle Publishing", 3 => "November- December 2013", 4 => "Engineering as a Service", 5 => "David A. Kelly");$catalog- >insert('catalog2', $columns); $slice = new ColumnSlice(1); var_dump( $catalog->get('catalog2', $slice)); echo "<br> "; echo "<br> "; $slice = new ColumnSlice(2, 5); var_dump( $catalog->get('catalog1', $slice)); echo "<br> "; echo "<br> "; $slice = new ColumnSlice('', '', $count=3); var_dump( $catalog->get('catalog1', $slice)); echo "<br> "; echo "<br> "; $slice = new ColumnSlice('', '', $count=5, $reversed=true); var_dump( $catalog->get('catalog1', $slice)); echo "<br> "; echo "<br> "; $slice = new ColumnSlice(3, '', $count=2, $reversed=true); var_dump( $catalog->get('catalog1', $slice)); $sys->drop_keyspace("catalogks"); $pool->close(); $sys->close(); ?>
Invoke the PHP script with the URL http://localhost:8000/phpcassa-master/scripts/column_slices.php. The results for the various ColumnSlice
examples are output. (See Figure 4.17.)
The ColumnFamily
class provides yet another method to fetch columns of data from the server:
get_range($key_start="",$key_finish="",$row_count=self::DEFAULT_ROW_COUNT, $column_slice=null,$column_names=null, $consistency_level=null, $buffer_size=null)
It fetches a range of rows and columns. The method parameters are discussed in Table 4.19.
Create a PHP script, get_range.php, in the phpcassa-masterscripts directory. As an example, specify the range using the default $key_start
and $key_finish
, which is to include all the keys. Specify the number of rows to fetch with $row_count
as 1000000
. Specifying a large number of rows does not fetch the rows if as many rows aren’t in the server. Specify the array of columns to fetch as array("1", "2","3", "4","5"))
, which fetches columns 1 to 5.
$rows = $catalog->get_range("", "", 1000000, null, array("1", "2","3", "4","5"));
The get_range()
method returns a phpcassaIteratorRangeColumnFamilyIterator
, which may be iterated over using a for
loop:
foreach($rows as $key => $columns) { echo $columns["1"]." ".$columns["2"]." ".$columns["3"]." ".$columns["4"]." ".$columns["5"]; }
If the $key_start
and $key_finish
are specified to be the same row, only one row is fetched. For example, the following invocation of get_range()
fetches the catalog1
row.
$rows = $catalog->get_range("catalog1", "catalog1", 1000000, null, array ("1", "2","3", "4","5"));
The get_range.php script appears in Listing 4.9.
Listing 4.9 The get_range.php Script
<?php require_once(__DIR__.'/../lib/autoload.php'), use phpcassaConnectionConnectionPool; use phpcassaColumnFamily; use phpcassaColumnSlice; use phpcassaSystemManager; use phpcassaSchemaStrategyClass; $sys = new SystemManager('127.0.0.1'), $sys->create_keyspace('ks', array( "strategy_class" => StrategyClass::SIMPLE_STRATEGY, "strategy_options" => array('replication_factor' => '1') )); $sys->create_column_family('ks', 'catalog', array( "column_type" => "Standard", "comparator_type" => "LongType", "key_validation_class" => "UTF8Type", "default_validation_class" => "UTF8Type" )); // Start a connection pool, create our ColumnFamily instance $pool = new ConnectionPool('ks', array('127.0.0.1')); $catalog = new ColumnFamily($pool, 'catalog'), $columns = array(1 => "Oracle Magazine", 2 => "Oracle Publishing", 3 => "November- December 2013", 4 => "Quintessential and Collaborative", 5 => "Tom Haunert");$ catalog->insert('catalog1', $columns); $columns = array(1 => "Oracle Magazine", 2 => "Oracle Publishing", 3 => "November- December 2013", 4 => "Engineering as a Service", 5 => "David A. Kelly");$catalog- >insert('catalog2', $columns); $rows = $catalog->get_range("", "", 1000000, null, array("1", "2","3", "4","5")); foreach($rows as $key => $columns) { echo $columns["1"]." ".$columns["2"]." ".$columns["3"]." ".$columns["4"]." ".$columns["5"]; } //$rows = $catalog->get_range("catalog1", "catalog1", 1000000, null, array("1", "2","3", "4","5")); //foreach($rows as $key => $columns) { // echo $columns["1"]." ".$columns["2"]." ".$columns["3"]." ".$columns["4"]." ".$columns["5"]; //} $sys->drop_keyspace("ks"); $pool->close(); $sys->close(); ?>
Invoke the PHP script with the URL http://localhost:8000/phpcassa-master/scripts/get_range.php. All the columns from the two rows in the database are output. (See Figure 4.18.)
In the example in which $key_start
is the same as the $key_finish
, only the specified key, catalog1
, is output. (See Figure 4.19.)
In this section, you will update data. Create a PHP script, update.php, in the phpcassamasterscripts directory. The insert()
method, which you used to add data, may also be used to update data. In the update.php script, add catalog1
and catalog2
rows to the catalog_update
column family in the catalog_update
keyspace. The required keyspace and column family are created in the script. Create a ConnectionPool
and a ColumnFamily
instance as before. Add data using the insert()
method. Then invoke the insert()
method again but with slightly modified column values. Output the column names and values before modification and after modification. The update.php script appears in Listing 4.10.
Listing 4.10 The update.php Script
<?php require_once(__DIR__.'/../lib/autoload.php'), use phpcassaConnectionConnectionPool; use phpcassaColumnFamily; use phpcassaSystemManager; use phpcassaSchemaStrategyClass; $sys = new SystemManager('127.0.0.1'), $sys->create_keyspace('catalog_update', array( "strategy_class" => StrategyClass::SIMPLE_STRATEGY, "strategy_options" => array('replication_factor' => '1'))); $sys->create_column_family('catalog_update', 'catalog', array( "column_type" => "Standard", "comparator_type" => "UTF8Type", "key_validation_class" => "UTF8Type", "default_validation_class" => "UTF8Type" )); $pool = new ConnectionPool('catalog_update', array('127.0.0.1')); $catalog = new ColumnFamily($pool, 'catalog'), $catalog->insert('catalog1', array("journal" => "Oracle Magazine", "publisher" => "Oracle Publishing", "edition" => "November December 2013", "title" => "Engineering as a Service","author" => "David A. Kelly")); echo 'Catalog catalog1 before modification '; echo "<br> "; $columns = $catalog->get('catalog1'), echo "Journal: ".$columns["journal"]." "; echo "Publisher: ".$columns["publisher"]." "; echo "Edition: ".$columns["edition"]." "; echo "Title: ".$columns["title"]." "; echo "Author: ".$columns["author"]." "; echo "<br> "; $catalog->insert('catalog1', array("journal" => "Oracle-Magazine", "publisher" => "Oracle-Publishing","edition" => "November-December-2013", "title" => "Engineering as a Service","author" => "Kelly, David A.")); echo 'Catalog catalog1 after modification '; echo "<br> "; $columns = $catalog->get('catalog1'), echo "Journal: ".$columns["journal"]." "; echo "Publisher: ".$columns["publisher"]." "; echo "Edition: ".$columns["edition"]." "; echo "Title: ".$columns["title"]." "; echo "Author: ".$columns["author"]." "; echo "<br> "; $sys->drop_keyspace("catalog_update"); $pool->close(); $sys->close(); ?>
Invoke the PHP script with the URL http://localhost:8000/phpcassa-master/scripts/update.php. All the columns from the two rows in the database are output before and after the update. (See Figure 4.20.)
Next, you will delete the data added and also delete the column family and keyspace.
The ColumnFamily
provides the following method to remove columns from a row:
remove($key, $column_names=null, $consistency_level=null)
The method parameters are discussed in Table 4.20.
Create a PHP script, delete.php, in the phpcassa-masterscripts directory. Then create a ColumnFamily
instance as before. The remove()
method must be invoked for each row key to remove. Remove the catalog1
and catalog2
rows.
$catalog->remove("catalog1"); $catalog->remove("catalog2");
The delete.php script appears in Listing 4.11.
Listing 4.11 The delete.php Script
<?php require_once(__DIR__.'/../lib/autoload.php'), use phpcassaConnectionConnectionPool; use phpcassaColumnFamily; use phpcassaSystemManager; $sys = new SystemManager('127.0.0.1'), $pool = new ConnectionPool('php_catalog', array('127.0.0.1')); $catalog = new ColumnFamily($pool, 'catalog'), $catalog->remove("catalog1"); $catalog->remove("catalog2"); //$catalog->remove("catalog3"); //$catalog->remove("catalog4"); //$catalog->remove("catalog5"); echo 'Catalog ids catalog1 and catalog2 removed'; ?>
Invoke the PHP script with the URL http://localhost:8000/phpcassa-master/scripts/delete. php. The two rows, catalog1
and catalog2
, are removed. (See Figure 4.21.)
The SystemManager
class provides the methods discussed in Table 4.21 to remove a column family or data from a column family as well as to remove a keyspace.
The ColumnFamily
class provides the truncate()
method to delete all data from a column family. Create a PHP script, dropCFKeyspace.php, in the phpcassa-masterscripts directory. Then create a ColumnFamily
instance as before.
$sys = new SystemManager('127.0.0.1'), $pool = new ConnectionPool('php_catalog', array('127.0.0.1')); $catalog = new ColumnFamily($pool, 'catalog'),
Next, invoke the truncate()
method to remove all data from the column family. Invoke the drop_keyspace( mixed $keyspace )
method to delete the php_catalog
keyspace.
$catalog->truncate(); $sys->drop_keyspace("php_catalog");
The dropCFKeyspace.php script appears in Listing 4.12.
Listing 4.12 The dropCFKeyspace.php Script
<?php require_once(__DIR__.'/../lib/autoload.php'), use phpcassaConnectionConnectionPool; use phpcassaColumnFamily; use phpcassaSystemManager; use phpcassaSchemaStrategyClass; $sys = new SystemManager('127.0.0.1'), $pool = new ConnectionPool('php_catalog', array('127.0.0.1')); $catalog = new ColumnFamily($pool, 'catalog'), $catalog->truncate(); $sys->drop_keyspace("php_catalog"); $pool->close(); $sys->close(); echo 'removed Column Family and Keyspace'; ?>
Invoke the PHP script with the URL http://localhost:8000/phpcassa-master/scripts/dropCFKeyspace.php. The column family is truncated, but is not removed. Subsequently, the keyspace is removed, which also removes the column family. (See Figure 4.22.)
This chapter discussed the phpcassa PHP client library for Apache Cassandra to connect to Cassandra server, create a keyspace, create a column family, add data, fetch data, update data, delete data, and drop the keyspace. In the next chapter, you will use the Ruby client for Cassandra to access Cassandra and perform similar create, read, update, delete (CRUD) operations.
18.223.108.119