simy / db
A lightweight, dependency-free PHP 8+ DB layer for SQLite3 with fluent query builder interface
Requires
- php: ^8.1
- ext-sqlite3: *
README
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
- Fork the repository
- Create a feature branch: git checkout -b feature/new-feature
- Make your changes and add tests
- Commit your changes: git commit -am 'Add new feature'
- Push to the branch: git push origin feature/new-feature
- 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