Download the PHP package mroosz/php-cassandra without Composer
On this page you can find all versions of the php package mroosz/php-cassandra. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package php-cassandra
php-cassandra: A modern Cassandra client for PHP
php-cassandra is a pure-PHP client for Apache Cassandra with support for CQL binary protocol v3, v4 and v5 (Cassandra 4.x/5.x), synchronous and asynchronous APIs, prepared statements, batches, result iterators, object mapping, SSL/TLS, and LZ4 compression.
Packagist: mroosz/php-cassandra
Repository: GitHub – MichaelRoosz/php-cassandra
Table of contents
- php-cassandra: A modern Cassandra client for PHP
- Table of contents
- Introduction
- Why choose php-cassandra?
- Key Features
- Requirements
- System Requirements
- PHP Extensions
- Data Type Compatibility
- Installation
- Using Composer (Recommended)
- Without Composer
- Quick start
- Basic Connection and Query
- Prepared statements
- Async Operations Example
- Error Handling Example
- SSL/TLS Connection Example
- Connecting
- Consistency levels
- Queries
- Prepared statements
- Batches
- Results and fetching
- Object mapping
- Data types
- Type definition syntax for complex values
- Events
- Tracing and custom payloads (advanced)
- Asynchronous API
- Compression
- Error handling
- Exception Hierarchy
- Error Handling Patterns
- Basic Error Handling
- Specific Server Error Handling
- Retry Logic with Exponential Backoff
- Timeout Handling
- Error Information Access
- Configuration Reference
- Connection Configuration
- Node Configuration
- Connection Options
- Request Options
- Query Options
- Execute Options
- Prepare Options
- Batch Options
- Advanced Configuration
- Value Encoding Configuration
- Event Listeners
- Notes
- Frequently Asked Questions (FAQ)
- General Questions
- Installation and Setup
- Data Types and Modeling
- Migration Guide
- From DataStax PHP Driver
- Connection Setup
- Query Execution
- Prepared Statements
- Data Types
- Async Operations
- Migration Checklist
- Connection tuning examples
- Configuring value encoding
- Warnings listener
- Event processing patterns
- v5 keyspace per request
- Tracing notes
- Performance tips
- Version support
- API reference (essentials)
- Changelog
- License
- Contributing
- Development Setup
- Contribution Guidelines
- Code Standards
- Contributors
- Supporting the Project
Introduction
php-cassandra is a modern PHP client for Apache Cassandra that prioritizes correctness, performance, and developer experience. This library aims to provide full protocol coverage and advanced features while maintaining simplicity.
Why choose php-cassandra?
🚀 Modern Architecture
- Pure PHP implementation with no external dependencies
- Support for latest Cassandra protocol versions (v3/v4/v5)
- Built for PHP 8.1+ with modern language features
⚡ High Performance
- Asynchronous request pipelining for maximum throughput
- LZ4 compression support for reduced bandwidth
- Prepared statement caching and reuse
🎯 Developer Friendly
- Complete data type coverage including complex nested structures
- Rich configuration options with sensible defaults
- Object mapping with customizable row classes
Key Features
- Protocol Support: v3/v4/v5 with automatic negotiation
- Transports: Sockets and PHP streams (SSL/TLS, persistent connections)
- Request Types: Synchronous, Asynchronous
- Statements: Prepared statements with positional/named binding, auto-prepare
- Data Types: Full coverage including collections, tuples, UDTs, custom types, vectors
- Results: Iterators, multiple fetch styles, object mapping
- Events: Schema/status/topology change notifications
- Advanced: LZ4 compression, server overload signaling, tracing support
Requirements
System Requirements
Component | Minimum | Recommended | Notes |
---|---|---|---|
PHP Version | 8.1.0 | 8.3+ | Latest stable version recommended |
Architecture | 32-bit/64-bit | 64-bit | 64-bit required for Bigint/Counter/Date/Duration/Time/Timestamp types and defaultTimestamp request option (unsupported on 32-bit) |
PHP Extensions
Extension | Required | Purpose | Notes |
---|---|---|---|
sockets | Optional | Socket transport | Required for sockets connections configured with SocketNodeConfig |
bcmath or gmp | Optional | Performance improvement for large integer operations | Used by Varint and Decimal types |
openssl | Optional | SSL/TLS connections | Required for encrypted connections |
Data Type Compatibility
Some Cassandra data types require 64-bit PHP and are unsupported on 32-bit:
Type | 32-bit PHP | 64-bit PHP | Notes |
---|---|---|---|
Bigint |
⚠️ Partial | ✅ Full | Supported if the value is within 32-bit range |
Counter |
⚠️ Partial | ✅ Full | Supported if the value is within 32-bit range |
Date |
❌ Unsupported | ✅ Full | Requires 64-bit PHP |
Duration |
❌ Unsupported | ✅ Full | Requires 64-bit PHP |
Time |
❌ Unsupported | ✅ Full | Requires 64-bit PHP |
Timestamp |
❌ Unsupported | ✅ Full | Requires 64-bit PHP |
Additionally, the defaultTimestamp
request option (in QueryOptions
and BatchOptions
) requires 64-bit PHP and is unsupported on 32-bit.
Installation
Using Composer (Recommended)
Then include Composer's autoloader in your application entrypoint (if not already):
Without Composer
If you can't use Composer, you can load the library's own autoloader:
Quick start
Basic Connection and Query
Prepared statements
Async Operations Example
Error Handling Example
SSL/TLS Connection Example
Connecting
Create NodeConfig
instances and pass them to Connection
:
Connection options are provided via ConnectionOptions
:
enableCompression
= use LZ4 if enabled on serverthrowOnOverload
= true to ask server to throw on overload (v4+)nodeSelectionStrategy
=Random
(default) orRoundRobin
preparedResultCacheSize
= cache size for prepared metadata (default 100)
Keyspace selection:
- v5: can also be sent per-request via Query/Execute options (see below)
- v3/v4: call
$conn->setKeyspace('ks')
or runUSE ks
Consistency levels
Use the Consistency
enum:
ALL
,ANY
,EACH_QUORUM
,LOCAL_ONE
,LOCAL_QUORUM
,LOCAL_SERIAL
,ONE
,QUORUM
,SERIAL
,THREE
,TWO
Apply per call or as default via setConsistency()
.
Queries
Synchronous:
Asynchronous:
Query options (QueryOptions
):
autoPrepare
(bool, default true): transparently prepare+execute when neededpageSize
(int, min 100 enforced by client)pagingState
(string)serialConsistency
(SerialConsistency::SERIAL
orSerialConsistency::LOCAL_SERIAL
)defaultTimestamp
(microseconds since epoch)- Requires 64-bit PHP; unsupported on 32-bit
namesForValues
(bool): true to use associative binds; if not explicitly set, it is auto-detected for queries and executeskeyspace
(string; protocol v5 only)nowInSeconds
(int; protocol v5 only)
Notes:
- If you supply non-
Value\*
PHP values withQueryOptions(autoPrepare: true)
, the driver auto-prepares + executes for correct typing. - Always use fully-qualified table names (including keyspace) for
PREPARE
statements to avoid ambiguity, e.g.SELECT ... FROM ks.users WHERE ...
.
Fetch all pages helpers:
Prepared statements
Pagination with prepared statements:
Execute all pages helper:
Additional notes:
- For
PREPARE
andEXECUTE
,namesForValues
is auto-detected if not set explicitly based on the array keys (associative vs indexed). - Always use fully-qualified table names in prepared statements.
Batches
Batch notes:
- BATCH does not support names for values at the protocol level for simple queries; use positional values for
appendQuery
. For prepared entries, provide values consistent with the prepared statement (associative for named markers). BatchOptions
:serialConsistency
,defaultTimestamp
(64-bit PHP only),keyspace
(v5),nowInSeconds
(v5).
Results and fetching
query()
/execute()
return a Result
; call asRowsResult()
for row-returning queries. Supported RowsResult
methods:
fetch(FetchType::ASSOC|NUM|BOTH)
returns next row or falsefetchAll(FetchType)
returns all remaining rowsfetchColumn(int $index)
/fetchAllColumns(int $index)
fetchKeyPair(int $keyIndex, int $valueIndex)
/fetchAllKeyPairs(...)
getIterator()
returns aResultIterator
so you canforeach ($rowsResult as $row)
Example:
Advanced fetching examples:
Pagination example:
Object mapping
You can fetch rows into objects by implementing RowClassInterface
or by using the default RowClass
:
Data types
All native Cassandra types are supported via classes in Cassandra\Value\*
. You may pass either:
- A concrete
Value\...
instance, or - A PHP scalar/array matching the type; the driver will convert it when metadata is available
Examples:
Type definition syntax for complex values
For complex types, the driver needs a type definition to encode PHP values. Wherever you see a parameter like \Cassandra\Type|(array{ type: \Cassandra\Type }&array<mixed>)
, you can either pass a scalar Type::...
(for simple elements) or a definition array with nested types for complex structures. The common shapes are:
- List:
['type' => Type::LIST, 'valueType' => <elementType>, 'isFrozen' => bool]
- Set:
['type' => Type::SET, 'valueType' => <elementType>, 'isFrozen' => bool]
- Map:
['type' => Type::MAP, 'keyType' => <keyType>, 'valueType' => <valueType>, 'isFrozen' => bool]
- Tuple:
['type' => Type::TUPLE, 'valueTypes' => [<t1>, <t2>, ...]]
- UDT:
['type' => Type::UDT, 'valueTypes' => ['field' => <type>, ...], 'isFrozen' => bool, 'keyspace' => 'ks', 'name' => 'udt_name']
- Vector:
['type' => Type::VECTOR, 'valueType' => <elementType>, 'dimensions' => int]
Examples
Nested complex example (Set
Special values:
new \Cassandra\Value\NotSet()
encodes a bind variable as NOT SET (distinct from NULL)
Events
Register a listener and subscribe for events on the connection:
Non-blocking event polling:
Tracing and custom payloads (advanced)
You can enable tracing and set a custom payload on any request:
Asynchronous API
The async API lets you pipeline multiple requests without blocking. Each async method returns a Cassandra\Statement
handle that you can resolve later.
You now have both blocking and non-blocking control:
- Blocking per statement:
getResult()
/getRowsResult()
/waitForResponse()
- Blocking for sets:
waitForStatements(array $statements)
andwaitForAllPendingStatements()
- Non-blocking/polling:
drainAvailableResponses(int $max = PHP_INT_MAX): int
— processes up tomax
responses if availabletryResolveStatement(Statement $statement): bool
— resolves a specific statement if possibletryResolveStatements(array $statements, int $max = PHP_INT_MAX): int
— resolves from a set without blockingwaitForAnyStatement(array $statements): Statement
— blocks until any of the given statements completes
Basics:
Waiting for all responses:
Non-blocking draining and polling:
Prepared + async:
Advanced waiting:
Compression
Enable LZ4 compression (if supported by the server) via ConnectionOptions
:
Notes:
- Compression is negotiated during STARTUP. When enabled, the client accepts server-compressed frames and transparently decompresses them.
- The client may still send some frames uncompressed depending on size/heuristics; this is allowed by the protocol.
Error handling
php-cassandra provides comprehensive error handling with a well-structured exception hierarchy. Understanding these exceptions helps you build robust applications with proper error recovery.
Exception Hierarchy
Error Handling Patterns
Basic Error Handling
Specific Server Error Handling
Retry Logic with Exponential Backoff
Timeout Handling
Error Information Access
Most server exceptions provide additional context:
Configuration Reference
Connection Configuration
Node Configuration
StreamNodeConfig (supports SSL/TLS, persistent connections)
SocketNodeConfig (requires ext-sockets
)
Connection Options
Request Options
Query Options
Execute Options
Prepare Options
Batch Options
Advanced Configuration
Value Encoding Configuration
Event Listeners
Notes
pageSize
is clamped to a minimum of 100 by the client for efficiency.- If you supply non-
Value\*
PHP values withQueryOptions(autoPrepare: true)
, the driver auto-prepares + executes for correct typing. - On
UNPREPARED
server errors, the driver transparently re-prepares and retries the execution. - Always use fully-qualified table names in
PREPARE
statements.
Frequently Asked Questions (FAQ)
General Questions
Q: What's the difference between this library and the DataStax PHP Driver?
A: The main differences are:
- Pure PHP: No C extensions required, easier deployment
- Protocol v5 Support: Full support for latest Cassandra protocol features
- Active Development: Actively maintained with regular updates
- Modern PHP: Built for PHP 8.1+ with modern language features
Q: Can I use this with older versions of Cassandra?
A: Yes! The library supports protocol versions v3, v4, and v5:
- Cassandra 2.1+: Protocol v3
- Cassandra 2.2+: Protocol v4 (recommended)
- Cassandra 4.0+: Protocol v5 (recommended for new deployments)
Installation and Setup
Q: Do I need any PHP extensions?
A: The library works with standard PHP, but some extensions enhance functionality:
ext-sockets
: Required for SocketNodeConfig (alternative: StreamNodeConfig)ext-bcmath
orext-gmp
: Improves performance for large integer operations (Varint, Decimal)ext-openssl
: For SSL/TLS connections
Q: Can I run this on 32-bit PHP?
A: Limited support. The following features are unsupported on 32-bit PHP: value types Bigint
, Counter
, Date
, Duration
, Time
, Timestamp
, and the defaultTimestamp
request option. Use 64-bit PHP for full compatibility.
Data Types and Modeling
Q: How do I handle complex data structures?
A: Use collections and UDTs:
Q: How do I work with timestamps?
A: Use the Timestamp value class:
Migration Guide
From DataStax PHP Driver
If you're migrating from the DataStax PHP Driver, here are the key differences and migration steps:
Connection Setup
Query Execution
Prepared Statements
Data Types
Async Operations
Migration Checklist
- [ ] Update connection setup - Replace cluster builder with Connection and NodeConfig
- [ ] Update query methods - Replace execute() with query() and asRowsResult()
- [ ] Update data types - Replace Cassandra* types with Cassandra\Value* types
- [ ] Update prepared statements - Use new prepare/execute pattern
- [ ] Update async operations - Replace futures with statement handles
- [ ] Update error handling - Use new exception hierarchy
- [ ] Update batch operations - Use new Batch class
- [ ] Test thoroughly - Verify all functionality works as expected
Connection tuning examples
Configuring value encoding
Warnings listener
Event processing patterns
v5 keyspace per request
- When the server negotiates protocol v5, you can set
keyspace
onQueryOptions
,ExecuteOptions
, andPrepareOptions
. - If you also call
setKeyspace()
, the per-request option takes precedence for that request.
Tracing notes
- Use tracing sparingly in production; it adds overhead.
- Read the trace id from the result to correlate with server logs (if enabled).
Performance tips
- Prefer prepared statements for hot paths; the driver caches prepared metadata.
- Iterate results instead of materializing large arrays.
Version support
- Cassandra 4.x/5.x tested. Protocols v3/v4/v5 supported; features like per-request keyspace/now_in_seconds require v5.
API reference (essentials)
-
Cassandra\Connection
connect()
,disconnect()
,isConnected()
,getVersion()
setConsistency(Consistency)
,withConsistency(Consistency)
setKeyspace(string)
,withKeyspace(string)
,supportsKeyspaceRequestOption()
,supportsNowInSecondsRequestOption()
query(string, array = [], ?Consistency, QueryOptions)
/queryAsync(...)
/queryAll(...)
prepare(string, PrepareOptions)
/prepareAsync(...)
execute(Result $previous, array = [], ?Consistency, ExecuteOptions)
/executeAsync(...)
/executeAll(...)
batch(Batch)
/batchAsync(Batch)
syncRequest(Request)
/asyncRequest(Request)
/waitForStatements(array $statements)
/waitForAllPendingStatements()
/waitForAnyStatement()
registerEventListener(EventListener)
/unregisterEventListener(EventListener)
/waitForNextEvent()
registerWarningsListener(WarningsListener)
/unregisterWarningsListener(WarningsListener)
waitForNextResponse()
- Non-blocking helpers:
drainAvailableResponses()
,tryResolveStatement()
,tryResolveStatements()
,tryReadNextResponse()
,tryReadNextEvent()
-
Results
RowsResult
(iterable):fetch()
,fetchAll()
,fetchColumn()
,fetchAllColumns()
,fetchKeyPair()
,fetchAllKeyPairs()
,configureFetchObject()
,fetchObject()
,fetchAllObjects()
,getRowsMetadata()
,hasMorePages()
PreparedResult
(for execute)SchemaChangeResult
,SetKeyspaceResult
,VoidResult
- Types
Cassandra\Consistency
(enum)Cassandra\SerialConsistency
(enum)Cassandra\Type
(enum) andCassandra\Value\*
classes (Ascii, Bigint, Blob, Boolean, Counter, Date, Decimal, Double, Duration, Float32, Inet, Int32, ListCollection, MapCollection, NotSet, SetCollection, Smallint, Time, Timestamp, Timeuuid, Tinyint, Tuple, UDT, Uuid, Varchar, Varint, Vector, ...)
Changelog
See CHANGELOG.md
for release notes and upgrade considerations.
License
This library is released under the MIT License. See LICENSE
for details.
Contributing
Contributions are welcome! Here's how to get started:
Development Setup
-
Fork and Clone
-
Install Dependencies
-
Start Development Environment
- Run Tests
Docker quickstart for integration tests:
Contribution Guidelines
Code Standards
- PHP 8.1+: Use modern PHP features and syntax
- PSR-12: Follow PHP-FIG coding standards
- Type Hints: Use strict typing everywhere possible
- Documentation: Document all public methods and classes
- Tests: Include tests for all new functionality
Contributors
- Michael Roosz - Current maintainer and lead developer
- Shen Zhenyu - Original driver development
- Evseev Nikolay - Foundation and early development
Special thanks to all contributors who have helped make this library better.
Supporting the Project
If you find this library useful, consider:
- ⭐ Starring the repository on GitHub
- 🐛 Reporting bugs and suggesting features
- 📝 Contributing code or documentation
- 💬 Sharing your experience with the community
- 📚 Writing tutorials or blog posts
Your support helps keep this project active and improving!