Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Phpcassa Laravel Package

thobbs/phpcassa

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation

    composer require thobbs/phpcassa
    

    Ensure your project meets the requirements (PHP 5.3+).

  2. Basic Connection

    use Phpcassa\Client;
    
    $client = new Client('127.0.0.1', 9160); // Default port for Cassandra 1.x
    $keyspace = $client->getKeyspace('your_keyspace');
    
  3. 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);
    
  4. Key Documentation

    • Phpcassa GitHub Wiki (if archived, check for cached versions).
    • Focus on the Client, Keyspace, and ColumnFamily classes for core functionality.

Implementation Patterns

Core Workflows

  1. Connection Management

    • Use a singleton pattern for the 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;
          }
      }
      
  2. Keyspace Operations

    • Dynamic Keyspace Switching: Store the keyspace name in config and switch as needed:
      $keyspaceName = config('cassandra.keyspace');
      $keyspace = $client->getKeyspace($keyspaceName);
      
  3. Batch Operations

    • Use 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();
      
  4. Pagination for Large Queries

    • Leverage getSlice() for efficient pagination:
      $result = $keyspace->getSlice('users', '', '', [
          'ColumnCount' => 100,
          'Range' => ['Start' => '', 'Finish' => 'z'],
      ]);
      
  5. Laravel Integration

    • Service Provider:
      public function register() {
          $this->app->singleton('cassandra', function ($app) {
              return new Client(config('cassandra.host'), config('cassandra.port'));
          });
      }
      
    • Facade:
      // 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'));
      }
      
  6. Error Handling

    • Wrap operations in try-catch blocks to handle Phpcassa_Exception:
      try {
          $result = $keyspace->get('users', 'nonexistent_user');
      } catch (Phpcassa_Exception $e) {
          Log::error("Cassandra error: " . $e->getMessage());
          return null;
      }
      

Gotchas and Tips

Pitfalls

  1. Deprecated API

    • Phpcassa is archived and lacks support for Cassandra 3.x+. Avoid for new projects; consider alternatives like:
  2. Connection Timeouts

    • Default timeout may be too short for slow networks. Adjust via Client constructor:
      $client = new Client('127.0.0.1', 9160, 5.0); // 5-second timeout
      
  3. Keyspace Assumption

    • Phpcassa assumes the keyspace exists. Always check or create it first:
      if (!$client->keyspaceExists('your_keyspace')) {
          $client->createKeyspace('your_keyspace', ['StrategyClass' => 'SimpleStrategy', 'ReplicationFactor' => 1]);
      }
      
  4. Thread Safety

    • The Client is not thread-safe. Use one instance per request in multi-threaded environments.
  5. Data Serialization

    • Phpcassa uses Thrift serialization under the hood. Complex PHP objects may not serialize correctly. Flatten data before insertion:
      // Bad: Complex object
      $keyspace->insert('users', 'user1', ['data' => $complexObject]);
      
      // Good: Flattened array
      $keyspace->insert('users', 'user1', ['data' => json_encode($complexObject)]);
      

Debugging Tips

  1. Enable Thrift Logging Add to your Client initialization:

    $client = new Client('127.0.0.1', 9160, 5.0, null, null, null, true); // Enable debug
    
  2. 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)
        }
    }
    
  3. 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');
    

Extension Points

  1. 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';
        }
    }
    
  2. 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);
        }
    }
    
  3. 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
        }
    }
    
  4. 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']));
            }
        }
    ]);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed