gitdb/client

Official PHP client for GitDB - GitHub-backed NoSQL database

v1.0.0 2025-07-13 10:21 UTC

This package is auto-updated.

Last update: 2025-07-13 10:31:46 UTC


README

Official PHP client for GitDB - GitHub-backed NoSQL database.

Installation

Install via Composer:

composer require gitdb/client

Or add to your composer.json:

{
    "require": {
        "gitdb/client": "^1.0"
    }
}

Requirements

  • PHP 8.0 or higher
  • Guzzle HTTP Client
  • JSON extension

Quick Start

<?php

require_once 'vendor/autoload.php';

use GitDB\GitDBClient;

// Create a client instance
$client = new GitDBClient('your-github-token', 'owner', 'repository');

// Insert a document
$document = [
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'age' => 30
];

$result = $client->insert('users', $document);
echo "Inserted document ID: " . $result['id'] . "\n";

// Find documents
$documents = $client->find('users', ['age' => ['$gte' => 25]]);
echo "Found " . count($documents) . " documents\n";

// Update a document
$update = ['age' => 31];
$client->update($result['id'], $update);

// Delete a document
$client->delete($result['id']);

Configuration

GitHub Token

You'll need a GitHub Personal Access Token with the following permissions:

  • repo - Full control of private repositories
  • workflow - Update GitHub Action workflows

Create a token at: https://github.com/settings/tokens

Client Initialization

use GitDB\GitDBClient;

// Basic initialization
$client = new GitDBClient('token', 'owner', 'repo');

// With custom base URL (for self-hosted instances)
$client = new GitDBClient('token', 'owner', 'repo', 'https://your-gitdb-server.com');

API Reference

Collections

Create Collection

$client->createCollection('users');

List Collections

$collections = $client->getCollections();
foreach ($collections as $collection) {
    echo $collection['name'] . "\n";
}

Documents

Insert Document

$document = [
    'name' => 'John Doe',
    'email' => 'john@example.com'
];

$result = $client->insert('users', $document);
// Returns: ['id' => 'doc_id', 'data' => $document]

Find Documents

// Find all documents in collection
$documents = $client->find('users');

// Find with query
$documents = $client->find('users', ['age' => ['$gte' => 25]]);

// Find with limit
$documents = $client->find('users', [], 10);

// Find with skip
$documents = $client->find('users', [], 10, 20);

Find One Document

$document = $client->findOne('users', ['email' => 'john@example.com']);
// Returns single document or null

Find by ID

$document = $client->findById('users', 'doc_id');
// Returns document or null

Update Document

$update = ['age' => 31];
$result = $client->update('doc_id', $update);
// Returns: ['id' => 'doc_id', 'data' => $updated_document]

Update Many Documents

$query = ['age' => ['$lt' => 18]];
$update = ['status' => 'minor'];
$result = $client->updateMany($query, $update);
// Returns: ['modifiedCount' => 5]

Delete Document

$result = $client->delete('doc_id');
// Returns: ['deletedCount' => 1]

Delete Many Documents

$query = ['status' => 'inactive'];
$result = $client->deleteMany($query);
// Returns: ['deletedCount' => 10]

Count Documents

$count = $client->count('users');
echo "Total users: $count\n";

// Count with query
$count = $client->count('users', ['age' => ['$gte' => 25]]);
echo "Users 25+: $count\n";

Distinct Values

$emails = $client->distinct('users', 'email');
// Returns array of unique email values

Query Operators

GitDB supports MongoDB-style query operators:

Comparison Operators

  • $eq - Equal
  • $ne - Not equal
  • $gt - Greater than
  • $gte - Greater than or equal
  • $lt - Less than
  • $lte - Less than or equal
  • $in - In array
  • $nin - Not in array

Logical Operators

  • $and - Logical AND
  • $or - Logical OR
  • $not - Logical NOT
  • $nor - Logical NOR

Element Operators

  • $exists - Field exists
  • $type - Field type

Array Operators

  • $all - All elements match
  • $elemMatch - Element matches
  • $size - Array size

Example Queries

// Complex query examples
$query = [
    '$and' => [
        ['age' => ['$gte' => 18]],
        ['$or' => [
            ['status' => 'active'],
            ['status' => 'pending']
        ]]
    ]
];

$documents = $client->find('users', $query);

// Array query
$query = ['tags' => ['$in' => ['php', 'database']]];
$documents = $client->find('posts', $query);

// Exists query
$query = ['email' => ['$exists' => true]];
$documents = $client->find('users', $query);

Error Handling

The SDK throws exceptions for various error conditions:

use GitDB\GitDBException;

try {
    $result = $client->insert('users', $document);
} catch (GitDBException $e) {
    echo "GitDB Error: " . $e->getMessage() . "\n";
    echo "Status Code: " . $e->getCode() . "\n";
} catch (Exception $e) {
    echo "General Error: " . $e->getMessage() . "\n";
}

Advanced Usage

Batch Operations

// Insert multiple documents
$documents = [
    ['name' => 'Alice', 'age' => 25],
    ['name' => 'Bob', 'age' => 30],
    ['name' => 'Charlie', 'age' => 35]
];

foreach ($documents as $doc) {
    $client->insert('users', $doc);
}

Pagination

$page = 1;
$limit = 10;
$skip = ($page - 1) * $limit;

$documents = $client->find('users', [], $limit, $skip);

Data Validation

// Validate document before insertion
function validateUser($document) {
    $errors = [];
    
    if (empty($document['name'])) {
        $errors[] = 'Name is required';
    }
    
    if (empty($document['email']) || !filter_var($document['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Valid email is required';
    }
    
    if (isset($document['age']) && (!is_numeric($document['age']) || $document['age'] < 0)) {
        $errors[] = 'Age must be a positive number';
    }
    
    return $errors;
}

$document = ['name' => 'John', 'email' => 'john@example.com', 'age' => 30];
$errors = validateUser($document);

if (empty($errors)) {
    $client->insert('users', $document);
} else {
    echo "Validation errors: " . implode(', ', $errors) . "\n";
}

Examples

User Management System

<?php

require_once 'vendor/autoload.php';

use GitDB\GitDBClient;

class UserManager {
    private $client;
    
    public function __construct($token, $owner, $repo) {
        $this->client = new GitDBClient($token, $owner, $repo);
    }
    
    public function createUser($name, $email, $age) {
        $user = [
            'name' => $name,
            'email' => $email,
            'age' => $age,
            'created_at' => date('Y-m-d H:i:s'),
            'status' => 'active'
        ];
        
        return $this->client->insert('users', $user);
    }
    
    public function findUserByEmail($email) {
        return $this->client->findOne('users', ['email' => $email]);
    }
    
    public function updateUserStatus($userId, $status) {
        return $this->client->update($userId, ['status' => $status]);
    }
    
    public function getActiveUsers() {
        return $this->client->find('users', ['status' => 'active']);
    }
    
    public function deleteInactiveUsers() {
        return $this->client->deleteMany(['status' => 'inactive']);
    }
}

// Usage
$userManager = new UserManager('your-token', 'owner', 'repo');

// Create user
$user = $userManager->createUser('John Doe', 'john@example.com', 30);

// Find user
$foundUser = $userManager->findUserByEmail('john@example.com');

// Update status
$userManager->updateUserStatus($user['id'], 'inactive');

// Get active users
$activeUsers = $userManager->getActiveUsers();

Troubleshooting

Common Issues

  1. Authentication Error

    • Verify your GitHub token is valid
    • Ensure token has required permissions
    • Check token hasn't expired
  2. Repository Access

    • Verify repository exists
    • Check you have access to the repository
    • Ensure repository is not private (unless using private GitDB)
  3. Network Issues

    • Check internet connection
    • Verify GitHub API is accessible
    • Check firewall settings
  4. Rate Limiting

    • GitHub API has rate limits
    • Implement exponential backoff for retries
    • Consider using authenticated requests

Debug Mode

Enable debug mode to see detailed request/response information:

// Set debug mode (if supported by the client)
$client->setDebug(true);

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

Changelog

v1.0.0

  • Initial release
  • Full CRUD operations
  • Query support with MongoDB-style operators
  • Error handling
  • Comprehensive documentation