-
Notifications
You must be signed in to change notification settings - Fork 1
Client php
Official PHP client for ThemisDB - A high-performance multi-model database with native LLM integration.
- β Full Type Safety - Modern PHP with type hints
- β Transaction Support - BEGIN/COMMIT/ROLLBACK with isolation levels
- β Multi-Model - Relational, Graph, Vector operations
- β Query Support - AQL (Advanced Query Language)
- β Topology-Aware - Automatic shard routing with consistent hashing
- β Batch Operations - Efficient bulk operations
- β Vector Search - Similarity search for LLM/AI applications
- β Graph Operations - Traverse, shortest path, neighbors
- β Retry Logic - Automatic retries for failed requests
- β Connection Pooling - Efficient HTTP connection management
- PHP >= 7.4
- ext-curl
- ext-json
Install via Composer:
composer require themisdb/themisdb-phpOr add to your composer.json:
{
"require": {
"themisdb/themisdb-php": "^1.0"
}
}<?php
require_once 'vendor/autoload.php';
use ThemisDB\ThemisClient;
// Create client
$client = new ThemisClient(['http://localhost:8080']);
// Basic CRUD
$client->put('relational', 'users', 'user1', ['name' => 'Alice', 'age' => 30]);
$user = $client->get('relational', 'users', 'user1');
print_r($user);
// Delete
$client->delete('relational', 'users', 'user1');ThemisDB supports ACID transactions with BEGIN/COMMIT/ROLLBACK semantics.
<?php
use ThemisDB\ThemisClient;
$client = new ThemisClient(['http://localhost:8080']);
// Begin a transaction
$tx = $client->beginTransaction();
try {
// Perform operations within the transaction
$tx->put('relational', 'accounts', 'acc1', ['balance' => 1000]);
$tx->put('relational', 'accounts', 'acc2', ['balance' => 500]);
// Read within transaction
$acc1 = $tx->get('relational', 'accounts', 'acc1');
echo "Account 1 balance: {$acc1['balance']}\n";
// Commit the transaction
$tx->commit();
} catch (Exception $e) {
// Rollback on error
$tx->rollback();
throw $e;
}ThemisDB supports three isolation levels:
-
READ_COMMITTED(default) β Prevents dirty reads. Non-repeatable reads and phantom reads are possible. -
SNAPSHOTβ Provides a consistent snapshot of the database as of transaction start.β οΈ Write-skew and phantom-read anomalies are possible at SNAPSHOT isolation. Two concurrent SNAPSHOT transactions reading the same rows and writing disjoint keys can both commit even when their combined effect violates an application invariant (e.g. double-booking, over-withdrawal). UseSERIALIZABLEfor strict correctness. -
SERIALIZABLEβ Full serializability via SSI / predicate locking. Prevents write skew and phantom reads. May abort more transactions and has higher latency than SNAPSHOT.
<?php
// Use SNAPSHOT isolation for repeatable reads
// WARNING: write skew and phantom reads are possible at this level
$tx = $client->beginTransaction(['isolation_level' => 'SNAPSHOT']);
// Use SERIALIZABLE to prevent write skew and phantom reads
$tx = $client->beginTransaction(['isolation_level' => 'SERIALIZABLE']);
try {
$user1 = $tx->get('relational', 'users', 'user1');
$user2 = $tx->get('relational', 'users', 'user2');
// These reads are from the same snapshot
// even if other transactions modify the data
$tx->commit();
} catch (Exception $e) {
$tx->rollback();
throw $e;
}<?php
function transferMoney($client, $fromAccount, $toAccount, $amount) {
$tx = $client->beginTransaction(['isolation_level' => 'SNAPSHOT']);
try {
// Read both accounts
$fromAcc = $tx->get('relational', 'accounts', $fromAccount);
$toAcc = $tx->get('relational', 'accounts', $toAccount);
if (!$fromAcc || !$toAcc) {
throw new Exception('Account not found');
}
if ($fromAcc['balance'] < $amount) {
throw new Exception('Insufficient funds');
}
// Update balances
$fromAcc['balance'] -= $amount;
$toAcc['balance'] += $amount;
$tx->put('relational', 'accounts', $fromAccount, $fromAcc);
$tx->put('relational', 'accounts', $toAccount, $toAcc);
$tx->commit();
} catch (Exception $e) {
$tx->rollback();
throw $e;
}
}
// Usage
$client = new ThemisClient(['http://localhost:8080']);
transferMoney($client, 'alice', 'bob', 100.0);Efficiently process multiple entities in a single call:
<?php
use ThemisDB\ThemisClient;
$client = new ThemisClient(['http://localhost:8080']);
// Batch Put
$items = [
'user1' => ['name' => 'Alice', 'age' => 30],
'user2' => ['name' => 'Bob', 'age' => 25],
'user3' => ['name' => 'Charlie', 'age' => 35]
];
$result = $client->batchPut('relational', 'users', $items);
echo "Succeeded: " . count($result['succeeded']) . "\n";
echo "Failed: " . count($result['failed']) . "\n";
// Batch Get
$uuids = ['user1', 'user2', 'user3'];
$result = $client->batchGet('relational', 'users', $uuids);
print_r($result['found']); // Array of found entities
print_r($result['missing']); // Array of missing UUIDs
print_r($result['errors']); // Array of errors
// Batch Delete
$result = $client->batchDelete('relational', 'users', ['user1', 'user2']);Execute queries using ThemisDB's Advanced Query Language:
<?php
use ThemisDB\ThemisClient;
$client = new ThemisClient(['http://localhost:8080']);
// Simple query
$result = $client->query('FOR user IN users FILTER user.age > 25 RETURN user');
foreach ($result['items'] as $user) {
echo "{$user['name']} is {$user['age']} years old\n";
}
// Parameterized query
$result = $client->query(
'FOR user IN users FILTER user.city == @city RETURN user',
['params' => ['city' => 'Berlin']]
);
// Cursor-based pagination
$result = $client->query(
'FOR user IN users RETURN user',
[
'use_cursor' => true,
'batch_size' => 100
]
);
if ($result['has_more']) {
$nextPage = $client->query(
'FOR user IN users RETURN user',
[
'use_cursor' => true,
'cursor' => $result['next_cursor'],
'batch_size' => 100
]
);
}Perform graph traversals and path finding:
<?php
use ThemisDB\ThemisClient;
$client = new ThemisClient(['http://localhost:8080']);
// Traverse graph from a starting node
$nodes = $client->graphTraverse('user:alice', 3); // max depth 3
print_r($nodes);
// Find shortest path between two nodes
$path = $client->graphShortestPath('user:alice', 'user:charlie');
if ($path) {
echo "Path found: " . implode(' -> ', $path) . "\n";
}
// Get neighbors of a node
$neighbors = $client->graphNeighbors('user:alice', null, 'both'); // both directions
print_r($neighbors);
// Filter by edge type
$friends = $client->graphNeighbors('user:alice', 'FRIEND', 'out');
print_r($friends);Perfect for LLM and AI applications:
<?php
use ThemisDB\ThemisClient;
$client = new ThemisClient(['http://localhost:8080']);
// Upsert a vector
$embedding = array_fill(0, 768, 0.1); // 768-dimensional embedding
$client->vectorUpsert('doc1', $embedding, ['title' => 'AI Research Paper']);
// Search for similar vectors
$queryEmbedding = array_fill(0, 768, 0.15);
$results = $client->vectorSearch($queryEmbedding, 10); // top 10 results
foreach ($results['results'] as $result) {
echo "Document: {$result['id']}, Score: {$result['score']}\n";
}
// Search with metadata filter
$results = $client->vectorSearch(
$queryEmbedding,
10,
['category' => 'research'] // metadata filter
);
// Delete a vector
$client->vectorDelete('doc1');<?php
use ThemisDB\ThemisClient;
$client = new ThemisClient(
['http://localhost:8080', 'http://localhost:8081'], // Multiple endpoints
[
'namespace' => 'production', // Default: 'default'
'timeout' => 30.0, // Request timeout in seconds
'max_retries' => 3, // Maximum retry attempts
'metadata_endpoint' => null, // Custom metadata endpoint
'metadata_path' => '/_admin/cluster/topology' // Topology path
]
);<?php
use ThemisDB\ThemisClient;
use ThemisDB\NotFoundException;
use ThemisDB\TopologyException;
use ThemisDB\TransactionException;
$client = new ThemisClient(['http://localhost:8080']);
try {
$user = $client->get('relational', 'users', 'nonexistent');
// $user will be null for not found
if ($user === null) {
echo "User not found\n";
}
} catch (TopologyException $e) {
echo "Topology error: {$e->getMessage()}\n";
} catch (RuntimeException $e) {
echo "Request failed: {$e->getMessage()}\n";
}
// Transaction errors
try {
$tx = $client->beginTransaction();
$tx->put('relational', 'users', 'user1', ['name' => 'Alice']);
$tx->commit();
$tx->commit(); // Error: already committed
} catch (TransactionException $e) {
echo "Transaction error: {$e->getMessage()}\n";
}<?php
use ThemisDB\ThemisClient;
$client = new ThemisClient(['http://localhost:8080']);
// Check server health
$health = $client->health();
print_r($health);
// Check specific endpoint
$health = $client->health('http://localhost:8081');
print_r($health);The client automatically routes requests to the appropriate shard using consistent hashing:
<?php
use ThemisDB\ThemisClient;
// Client automatically fetches topology and routes requests
$client = new ThemisClient(['http://localhost:8080']);
// This request is routed to the correct shard based on the URN
$user = $client->get('relational', 'users', 'alice');
// For distributed deployments, provide all shard endpoints
$client = new ThemisClient([
'http://shard1.example.com:8080',
'http://shard2.example.com:8080',
'http://shard3.example.com:8080'
]);Perfect for websites with LLM support (WordPress, Laravel, etc.):
<?php
use ThemisDB\ThemisClient;
$client = new ThemisClient(['http://localhost:8080']);
// Store document embeddings from LLM
function storeDocument($client, $docId, $content, $embedding) {
// Store document
$client->put('document', 'docs', $docId, [
'content' => $content,
'created_at' => date('c')
]);
// Store embedding for similarity search
$client->vectorUpsert($docId, $embedding, [
'doc_id' => $docId,
'type' => 'document'
]);
}
// Retrieve similar documents for RAG (Retrieval-Augmented Generation)
function findSimilarDocuments($client, $queryEmbedding, $limit = 5) {
$results = $client->vectorSearch($queryEmbedding, $limit);
$documents = [];
foreach ($results['results'] as $result) {
$docId = $result['id'];
$doc = $client->get('document', 'docs', $docId);
$documents[] = [
'content' => $doc['content'],
'similarity' => $result['score']
];
}
return $documents;
}
// Example usage
$docEmbedding = generateEmbedding("Your document content here");
storeDocument($client, 'doc123', 'Your document content here', $docEmbedding);
$queryEmbedding = generateEmbedding("User query");
$similarDocs = findSimilarDocuments($client, $queryEmbedding);
// Use similar documents for context in LLM prompt
$context = implode("\n\n", array_column($similarDocs, 'content'));
$prompt = "Context:\n{$context}\n\nQuestion: How do I...?";<?php
// In your WordPress plugin or theme
use ThemisDB\ThemisClient;
// Initialize client
$themis = new ThemisClient(['http://localhost:8080']);
// Store post with metadata
add_action('save_post', function($post_id, $post) use ($themis) {
if ($post->post_type !== 'post' || $post->post_status !== 'publish') {
return;
}
$data = [
'title' => $post->post_title,
'content' => $post->post_content,
'author' => $post->post_author,
'date' => $post->post_date
];
$themis->put('relational', 'posts', (string)$post_id, $data);
}, 10, 2);
// Search posts using AQL
function search_posts_themis($query) {
global $themis;
$result = $themis->query(
'FOR post IN posts FILTER CONTAINS(post.title, @query) OR CONTAINS(post.content, @query) RETURN post',
['params' => ['query' => $query]]
);
return $result['items'];
}# Install dependencies
composer install
# Run tests
composer test
# Run static analysis
composer phpstan
# Check code style
composer cs-check
# Fix code style
composer cs-fixnew ThemisClient(array $endpoints, array $options = [])Options:
-
namespace(string) - Namespace for entities (default: 'default') -
timeout(float) - Request timeout in seconds (default: 30.0) -
max_retries(int) - Maximum retry attempts (default: 3) -
metadata_endpoint(string|null) - Custom metadata endpoint -
metadata_path(string) - Metadata path
get(string $model, string $collection, string $uuid): mixedput(string $model, string $collection, string $uuid, $data): booldelete(string $model, string $collection, string $uuid): boolbatchGet(string $model, string $collection, array $uuids): arraybatchPut(string $model, string $collection, array $items): arraybatchDelete(string $model, string $collection, array $uuids): arrayquery(string $aql, array $options = []): arraygraphTraverse(string $startNode, int $maxDepth = 3, ?string $edgeType = null): arraygraphShortestPath(string $startNode, string $endNode, ?string $edgeType = null): ?arraygraphNeighbors(string $node, ?string $edgeType = null, string $direction = 'both'): arrayvectorSearch(array $embedding, int $topK = 10, ?array $metadataFilter = null, array $options = []): arrayvectorUpsert(string $id, array $embedding, ?array $metadata = null): boolvectorDelete(string $id): boolbeginTransaction(array $options = []): Transactionhealth(?string $endpoint = null): array
-
getTransactionId(): string- Get transaction ID -
isActive(): bool- Check if transaction is active
get(string $model, string $collection, string $uuid): mixedput(string $model, string $collection, string $uuid, $data): booldelete(string $model, string $collection, string $uuid): boolquery(string $aql, array $options = []): arraycommit(): voidrollback(): void
MIT
- Documentation: https://makr-code.github.io/ThemisDB/
- GitHub Issues: Report bugs or request features
- Discussions: Community discussions
ThemisDB 1.9.0-beta Β· Home Β· Module-Index Β· GitHub Β· Issues
ThemisDB 1.9.0-beta Β· Home Β· Wiki-Index Β· Module-Index Β· FAQ Β· Quick-Reference Β· GitHub Β· Issues Β· Discussions Β· License
- Batch Operations
- Best Practices
- CRUD Tutorial
- Custom Document Ingestion
- Getting Started Tutorial
- Interactive Examples
- Schema Design
- Video Tutorials
- AQL Reference
- AQL Examples
- AQL Overview
- AQL Feature Roadmap
- AQL Geospatial Guide
- AQL LLM Migration Guide
- AQL API
- AQL Grammar (EBNF)
- AQL Root Overview
- AQL Examples (root)
- API Reference
- API Module README
- OpenAPI Overview
- Client SDK Overview
- SDK Overview
- Operations
- Operations Overview
- Operations Runbook
- Operations Handbook
- ThemisCtl Admin Guide
- Pipeline E2E SOPs
- Deploy Overview
- Docker Overview
- Docker Hub README
- Helm Overview
- Packaging Overview
- Operator Overview
- Security Policy
- Production Hardening Checklist
- Security Hardening Guide
- Encryption Key Management
- Access Control Framework
- Zero Trust Policy
- API Authentication & Authorization
- HSM Production Setup
- PKCS11 Integration
- DSGVO / SOC2 Checklist
- Access Model Runbooks
- Access Model Dashboard
- Maturity Automation Runbook
- Access Review Automation
- Access Model Dashboard
- Access Model Runbooks
- Rights Revocation
- Dr Checklists
- Dr Testing
- Incident Response Playbook
- Incident Response Testing
- GPU Oom Recovery
- Grammar Debugging
- Metrics Scrape Troubleshooting
- Model Swap Procedure
- Quota Tuning
- Subagent Deployment
- Logging Configuration
- Content Model
- Crypto & Keys
- Feature Flags Reference
- Modular Architecture Roadmap
- Modularization Guide
- Module Architecture Index
- PostgreSQL Wire Protocol
- Query Scheduling
- Raft Consensus Design
- Resource Pooling
- Source Directory Guide
- Unified Access Model
- E1 001 Layered Retrieval Design
- E1 002 Ann Abstraction Strategy
- E1 003 Tensor Summary Types
- E1 004 Lora Package Distinction
- E1 005 Model Switch Compatibility
- E1 006 Federated Tensor Summaries
- E2 001 Evaluation Framework Design
- E2 002 Hardware Profile Strategy
- E2 003 Query Planner Routing Model
- E2 004 Approximation Governance Rules
- E2 005 Cross Layer Fallback Confidence Policy
- E3 001 Distributed Tensor Design
- E3 002 Manifest Coordination Strategy
- E3 003 Recovery And Erasure Choice
- E3 004 Tensor Fabric Infrastructure
- Contributing
- Contributing (root)
- Code of Conduct
- Support
- Maintainers
- CTest Guide
- Build Quick Reference
- Developer Wiki Index
- Build / Test / CI
- Module Index
- Branching Strategy
- Disabled Stub Policy
- Docs PR Policy
- GA Promotion Sign Off
- Github Milestones Setup
- Maturity Claim Verification Checklist
- Maturity Evidence Registry
- Merge Gate Bot Config
- Merge Gate Status Live
- Phase 1 Closure Report
- Phase Closure Policy
- Phase Dependency Graph
- Phase3 Enforcement Runbook
- Plugin Submodule Rollback
- PR Version Targeting
- PR Version Targeting Backfill
- Production Ready 2026 Delivery Plan
- Query Module Status
- Readme
- Release Promotion Gate Policy
- Release Validation Checklist
- Security Module 5671 Evidence Summary
- Sharding P6 Residual Risk Acceptance
- Sourcecode Compliance Governance
- Updates Development Status Sign Off
- Wave C Implementation Complete
- Blob Storage
- Cuda
- Ethics Ai
- Exporters
- Huggingface
- Image Analysis
- Importers
- RPC
- Scraper
- Themisdb Ai Watermark Detector
- User Storage Encrypted
- Chimera Architecture
- Chimera Future
- Chimera Readme
- Chimera Roadmap
- Covina Fastapi Ingestion Architecture
- Covina Fastapi Ingestion Future
- Covina Fastapi Ingestion Roadmap
- Vcc Base Architecture
- Vcc Base Future
- Vcc Base Roadmap
- Vcc Clara Ingestion Architecture
- Vcc Clara Ingestion Future
- Vcc Clara Ingestion Roadmap
- Vcc Veritas Architecture
- Vcc Veritas Future
- Vcc Veritas Roadmap
- 01 Hello World
- 02 Todo App
- 03 Contact Manager
- 04 Inventory System
- 05 Time Series Monitor
- 06 Graph Social Network
- 07 Vector Search Documents
- 08 Dms Erp System
- 09 Iot Sensor Network
- 10 Drone Image Analysis
- 11 Blog Wiki
- 12 Expense Tracker
- 13 Recipe Manager
- 14 Ecommerce Catalog
- 15 Event Management
- 16 Kanban Board
- 17 Crm
- 18 Realtime Chat
- 19 Recommendation Engine
- 20 Smart Home
- 21 Coding Platform
- 22 AQL Diagram Tool
- 23 Traveling Salesman
- 24 Moral Philosophy Debates
- API Versioning
- Distributed Sharding
- Feedback Plugins
- Geo
- Gnn
- Image Analysis
- Legal Lora Training
- LLM
- Lora Sync
- Migration
- Nlp
- Performance
- Railway
- Replication
- Rope Visualization
- Sample Product Config
- Security
- Client SDK Overview
- Quickstart
- Sdk Enhancements
- Sdk Implementation Summary
- Test Suite Readme
- Go
- Java
- Javascript
- Php
- Python
- Ruby
- Rust
- Typescript
- 01 Grundlegende Operationen
- 02 AQL Queries
- 03 Graph Daten
- 04 Multimodell Anwendung
- 01 Quickstart Guide
- 02 AQL Referenz Kurzuebersicht
- 03 Datenmodellierung Guide
- 04 Uebungsaufgaben
- 05 Best Practices Guide
- Training Documents
- Training Overview
- 01 Einfuehrung Und Uebersicht
- 02 Datenmodelle Und Architektur
- 03 AQL Abfragesprache
- 04 Installation Und Setup
- 05 Anwendungsbeispiele
- Training Presentations
- Dependencies Readme
- Processmonitor Readme
- Themis.admintools.shared Readme
- Themis.aqlquerybuilder Readme
- Themis.aqlquerybuilder Roadmap
- Themis.auditlogviewer Readme
- Themis.auditlogviewer Roadmap
- Themis.classificationdashboard Readme
- Themis.classificationdashboard Roadmap
- Themis.compliancereports Readme
- Themis.compliancereports Roadmap
- Themis.gisviewer.controlpanel Readme
- Themis.gisviewer.controlpanel Roadmap
- Themis.impactanalysisviewer Readme
- Themis.impactanalysisviewer Roadmap
- Themis.ingestiontool Readme
- Themis.ingestiontool Roadmap
- Themis.keyrotationdashboard Readme
- Themis.keyrotationdashboard Roadmap
- Themis.piimanager Readme
- Themis.piimanager Roadmap
- Themis.retentionmanager Readme
- Themis.retentionmanager Roadmap
- Themis.sagaverifier Readme
- Themis.sagaverifier Roadmap
- Themis.usbadmintool Readme
- Themis.usbadmintool Roadmap
- CI Readme
- CI Roadmap
- Compiler Diagnostics Readme
- Compiler Diagnostics Roadmap
- Completion Readme
- Copilot Ollama Router Readme
- Copilot Ollama Router Roadmap
- Gnn Readme
- Gnn Roadmap
- Rope Visualizer Readme
- Rope Visualizer Roadmap
- Tco Calculator Readme
- Tco Calculator Roadmap
- Tests Readme
- Tests Roadmap
- Themis Config Wx Readme
- Themis Docs Builder Readme
- Wikipedia Ingestion Readme