simy/db

A lightweight, dependency-free PHP 8+ DB layer for SQLite3 with fluent query builder interface

v1.0.0 2025-08-24 22:43 UTC

This package is auto-updated.

Last update: 2025-08-25 11:54:05 UTC


README

Packagist Version PHP Version License

A modern, dependency-free PHP 8.1+ database abstraction layer for SQLite3 with fluent query builder interface, created by Elmahdi Abdallh.

๐Ÿ“ฆ Installation

Install via Composer:

composer require simy/db

Or clone the repository:

# Using SSH
git clone git@github.com:almhdy24/simydb.git
cd simydb

# Using HTTPS
git clone https://github.com/almhdy24/simydb.git
cd simydb

composer install

๐Ÿš€ Quick Start

<?php

require_once 'vendor/autoload.php';

use Simy\DB\Database;
use Simy\DB\DatabaseException;

try {
    // Create in-memory database
    $db = new Database('sqlite::memory:');
    
    // Create table using migration helper
    $migration = new MigrationHelper($db);
    $migration->createTable('users', [
        'id' => 'INTEGER PRIMARY KEY AUTOINCREMENT',
        'name' => 'TEXT NOT NULL',
        'email' => 'TEXT UNIQUE NOT NULL',
        'created_at' => 'DATETIME DEFAULT CURRENT_TIMESTAMP'
    ]);
    
    // Insert data
    $db->table('users')->insert([
        'name' => 'John Doe',
        'email' => 'john@example.com'
    ]);
    
    // Query data
    $user = $db->table('users')->where('id', 1)->first();
    print_r($user);
    
} catch (DatabaseException $e) {
    echo "Error: " . $e->getMessage();
}

โœจ Features

ยท ๐Ÿš€ PHP 8.1+ with strict typing and namespaces ยท ๐Ÿ“ฆ Zero dependencies - completely self-contained ยท ๐Ÿ”ง Fluent query builder inspired by Laravel Eloquent ยท ๐Ÿ›ก๏ธ Prepared statements and parameter binding for security ยท โšก SQLite3 optimized performance ยท ๐ŸŽฏ Comprehensive error handling with DatabaseException ยท ๐Ÿ”„ Full transaction support (begin, commit, rollback) ยท ๐Ÿ“Š Migration helper for schema management ยท ๐Ÿงช Unit-test friendly with in-memory database support ยท ๐Ÿ“ PSR-4 autoloading and clean code conventions

๐Ÿ“š Usage Examples

Basic CRUD Operations

// Insert records
$db->table('users')->insert([
    'name' => 'Jane Smith',
    'email' => 'jane@example.com'
]);

// Select all records
$users = $db->table('users')->get();

// Select with conditions
$user = $db->table('users')
    ->where('email', 'john@example.com')
    ->first();

// Update records
$db->table('users')
    ->update(['name' => 'John Updated'])
    ->where('id', 1);

// Delete records
$db->table('users')
    ->delete()
    ->where('id', 5);

Complex Queries

// Multiple where conditions
$users = $db->table('users')
    ->where('age', '>', 18)
    ->orWhere('status', 'active')
    ->orderBy('name', 'DESC')
    ->limit(10)
    ->get();

// Where IN clause
$users = $db->table('users')
    ->whereIn('id', [1, 2, 3, 5, 8])
    ->get();

// Count records
$count = $db->table('users')->where('active', 1)->count();

// Return as objects
$users = $db->table('users')->get(true);
foreach ($users as $user) {
    echo $user->name . "\n";
}

Transactions

$db->beginTransaction();

try {
    $db->table('users')->insert(['name' => 'User 1', 'email' => 'user1@example.com']);
    $db->table('profiles')->insert(['user_id' => $db->lastInsertId(), 'bio' => 'Test bio']);
    
    $db->commit();
    echo "Transaction successful!";
} catch (DatabaseException $e) {
    $db->rollback();
    echo "Transaction failed: " . $e->getMessage();
}

Error Handling

try {
    $db->table('nonexistent_table')->get();
} catch (DatabaseException $e) {
    echo "Error: " . $e->getMessage();
    echo "SQL: " . $e->getSql();
    echo "Params: " . json_encode($e->getParams());
    
    // Log for debugging
    error_log("Database error: " . $e->getMessage());
}

Schema Migrations

use Simy\DB\MigrationHelper;

$migration = new MigrationHelper($db);

// Create table
$migration->createTable('posts', [
    'id' => 'INTEGER PRIMARY KEY AUTOINCREMENT',
    'title' => 'TEXT NOT NULL',
    'content' => 'TEXT',
    'user_id' => 'INTEGER',
    'created_at' => 'DATETIME DEFAULT CURRENT_TIMESTAMP',
    'FOREIGN KEY (user_id) REFERENCES users(id)'
]);

// Add column
$migration->addColumn('users', 'age', 'INTEGER DEFAULT 0');

// Check if table or column exists
if ($migration->tableExists('users')) {
    echo "Users table exists!";
}

if ($migration->columnExists('users', 'email')) {
    echo "Email column exists!";
}

๐Ÿ—๏ธ API Reference

Database Class

ยท __construct(string $filename) - Create database connection ยท table(string $table): QueryBuilder - Get query builder for table ยท execute(string $sql, array $params = []): bool - Execute raw SQL ยท query(string $sql, array $params = [], bool $asObject = false): array - Query raw SQL ยท beginTransaction(): bool - Start transaction ยท commit(): bool - Commit transaction ยท rollback(): bool - Rollback transaction ยท lastInsertId(): int - Get last insert ID

QueryBuilder Class

ยท select(array $columns): self - Set columns to select ยท where(string $column, $operator, $value = null): self - Add where clause ยท orWhere(string $column, $operator, $value = null): self - Add OR where clause ยท whereIn(string $column, array $values): self - Add WHERE IN clause ยท orderBy(string $column, string $direction = 'ASC'): self - Add ordering ยท limit(int $limit): self - Set limit ยท offset(int $offset): self - Set offset ยท get(bool $asObject = false): array - Get all results ยท first(bool $asObject = false): ?array - Get first result ยท insert(array $data): bool - Insert record ยท update(array $data): self - Update records ยท delete(): self - Delete records ยท count(): int - Count records

๐Ÿงช Testing

Run the test suite:

# Run basic tests
composer test

# Or run directly
php test.php

๐Ÿ“Š Package Statistics

ยท Packagist: simy/db ยท GitHub: almhdy24/simydb ยท Downloads: https://img.shields.io/packagist/dt/simy/db ยท License: MIT

๐Ÿค Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/new-feature
  3. Make your changes and add tests
  4. Commit your changes: git commit -am 'Add new feature'
  5. Push to the branch: git push origin feature/new-feature
  6. Submit a pull request

๐Ÿ“ Changelog

v1.0.0 (2025-08-24)

ยท Initial release ยท Database connection management ยท Fluent query builder with CRUD operations ยท Transaction support ยท Migration helper for schema management ยท Comprehensive error handling ยท SQLite3 optimized implementation

๐Ÿ“„ License

MIT License. See LICENSE file for details.

๐Ÿ‘จโ€๐Ÿ’ป Author

Elmahdi Abdallh (almhdy24)

ยท GitHub: @almhdy24

๐Ÿ™ Acknowledgments

ยท Inspired by Laravel Eloquent and Medoo ยท Built with PHP 8.1+ best practices ยท Dependency-free design for maximum compatibility