Installation
composer require thobbs/phpcassa
Ensure your project meets the requirements (PHP 5.3+).
Basic Connection
use Phpcassa\Client;
$client = new Client('127.0.0.1', 9160); // Default port for Cassandra 1.x
$keyspace = $client->getKeyspace('your_keyspace');
First Use Case: Insert & Query Data
// Create a column family (table) if it doesn't exist
$keyspace->createColumnFamily('users', [
'ColumnType' => 'Standard',
'ComparatorType' => 'UTF8Type',
]);
// Insert data
$keyspace->insert('users', 'user1', [
'name' => 'John Doe',
'email' => 'john@example.com',
], ['timestamp' => time()]);
// Query data
$result = $keyspace->get('users', 'user1', ['name', 'email']);
print_r($result);
Key Documentation
Client, Keyspace, and ColumnFamily classes for core functionality.Connection Management
Client instance to avoid redundant connections:
class CassandraService {
private static $client;
public static function getClient() {
if (!self::$client) {
self::$client = new Client('127.0.0.1', 9160);
}
return self::$client;
}
}
Keyspace Operations
$keyspaceName = config('cassandra.keyspace');
$keyspace = $client->getKeyspace($keyspaceName);
Batch Operations
batch() for atomic writes across multiple rows:
$batch = $keyspace->batch();
$batch->insert('users', 'user2', ['name' => 'Jane Doe']);
$batch->insert('users', 'user3', ['name' => 'Bob Smith']);
$batch->execute();
Pagination for Large Queries
getSlice() for efficient pagination:
$result = $keyspace->getSlice('users', '', '', [
'ColumnCount' => 100,
'Range' => ['Start' => '', 'Finish' => 'z'],
]);
Laravel Integration
public function register() {
$this->app->singleton('cassandra', function ($app) {
return new Client(config('cassandra.host'), config('cassandra.port'));
});
}
// config/cassandra.php
return [
'host' => '127.0.0.1',
'port' => 9160,
'keyspace' => 'your_keyspace',
];
// app/Facades/Cassandra.php
public static function getKeyspace() {
return app('cassandra')->getKeyspace(config('cassandra.keyspace'));
}
Error Handling
Phpcassa_Exception:
try {
$result = $keyspace->get('users', 'nonexistent_user');
} catch (Phpcassa_Exception $e) {
Log::error("Cassandra error: " . $e->getMessage());
return null;
}
Deprecated API
datastax/php-driver (official driver).php-cassandra (modern fork).Connection Timeouts
Client constructor:
$client = new Client('127.0.0.1', 9160, 5.0); // 5-second timeout
Keyspace Assumption
if (!$client->keyspaceExists('your_keyspace')) {
$client->createKeyspace('your_keyspace', ['StrategyClass' => 'SimpleStrategy', 'ReplicationFactor' => 1]);
}
Thread Safety
Client is not thread-safe. Use one instance per request in multi-threaded environments.Data Serialization
// Bad: Complex object
$keyspace->insert('users', 'user1', ['data' => $complexObject]);
// Good: Flattened array
$keyspace->insert('users', 'user1', ['data' => json_encode($complexObject)]);
Enable Thrift Logging
Add to your Client initialization:
$client = new Client('127.0.0.1', 9160, 5.0, null, null, null, true); // Enable debug
Check Thrift Exceptions Wrap operations to inspect raw Thrift errors:
try {
$result = $keyspace->get('users', 'user1');
} catch (Exception $e) {
if ($e instanceof Phpcassa_Exception && $e->getCode() == 16) {
// Handle "Key not found" (16 = NOT_FOUND)
}
}
Verify Schema
Use describe_keyspace() and describe_column_family() to debug schema issues:
$keyspaceInfo = $client->describe_keyspace('your_keyspace');
$cfInfo = $keyspace->describe_column_family('users');
Custom Column Types
Extend Phpcassa_Column_Type for custom comparators (e.g., UUIDType):
class CustomType extends Phpcassa_Column_Type {
public function __construct() {
$this->name = 'CustomType';
$this->type = 'custom';
}
}
Middleware for Operations Create a decorator to add pre/post-processing:
class LoggingKeyspace {
private $keyspace;
public function __construct(Phpcassa_Keyspace $keyspace) {
$this->keyspace = $keyspace;
}
public function insert($cf, $key, $columns, $options = []) {
Log::debug("Inserting into $cf:$key", $columns);
return $this->keyspace->insert($cf, $key, $columns, $options);
}
}
Query Builder Pattern Abstract repetitive queries into a fluent interface:
class CassandraQueryBuilder {
private $keyspace;
public function __construct(Phpcassa_Keyspace $keyspace) {
$this->keyspace = $keyspace;
}
public function getUser($userId) {
return $this->keyspace->get('users', $userId, ['*']);
}
public function getUsersByEmail($email) {
// Implement secondary index query logic
}
}
Event Listeners Hook into Cassandra events (e.g., post-insert) using PHP events or callbacks:
$keyspace->insert('users', 'user1', ['name' => 'Alice'], [
'callback' => function ($success, $result) {
if ($success) {
event(new UserCreated($result['name']));
}
}
]);
How can I help you explore Laravel packages today?