https://github.com/mathsgod/light-db
https://github.com/mathsgod/light-db
Last synced: 4 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/mathsgod/light-db
- Owner: mathsgod
- License: mit
- Created: 2024-12-04T08:30:43.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2026-02-27T09:43:48.000Z (4 months ago)
- Last Synced: 2026-02-27T15:06:58.942Z (4 months ago)
- Language: PHP
- Size: 188 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://github.com/mathsgod/light-db)
[](https://www.php.net/)
[](https://github.com/mathsgod/light-db)
# Light-DB
Light-DB is a lightweight PHP ORM/database access layer built on top of Laminas DB, designed for modern PHP 8.1+ applications. It provides an Eloquent-like Model operation experience with support for auto-mapping, dynamic queries, relationship queries, JSON field operations, and pagination features.
## โจ Features
- ๐ **Modern PHP**: Built on PHP 8.1+ features with type declarations and modern PHP syntax
- ๐ **Multi-Database Support**: Based on Laminas DB, supports MySQL, PostgreSQL, SQLite, SQL Server and more
- ๐ฆ **Eloquent-Style**: Familiar Active Record pattern with Eloquent-like API
- ๐ฏ **Smart Queries**: Support for complex conditional queries, sorting, grouping, and aggregation functions
- ๐ **Pagination Support**: Built-in Laminas Paginator integration for easy pagination
- ๐ **JSON Fields**: Native support for JSON field operations with automatic serialization/deserialization
- ๐ **Relationship Queries**: Support for inter-model relationship queries and dynamic property access
- ๐งช **Comprehensive Testing**: 73+ test cases ensuring code quality and stability
- โก **High Performance**: Lazy loading and query optimization for excellent performance
## ๐ Requirements
- PHP 8.1 or higher
- PDO extension
- Supported databases: MySQL, PostgreSQL, SQLite, SQL Server, etc.
## ๐ Installation
Install via Composer:
```bash
composer require mathsgod/light-db
```
## โ๏ธ Configuration
Create a `.env` file in your project root:
```env
DATABASE_DRIVER=pdo_mysql
DATABASE_HOSTNAME=localhost
DATABASE_PORT=3306
DATABASE_DATABASE=your_database
DATABASE_USERNAME=your_username
DATABASE_PASSWORD=your_password
DATABASE_CHARSET=utf8mb4
```
## ๐ฏ Basic Usage
### Defining Models
```php
'Raymond Chong',
'email' => 'raymond@example.com',
'age' => 30
]);
$user->save();
// Method 2: Direct property assignment
$user = User::Create();
$user->name = 'John Doe';
$user->email = 'john@example.com';
$user->save();
```
#### Querying Records
```php
// Query by primary key
$user = User::Get(1);
// Basic queries
$users = User::Query(['status' => 'active'])->toArray();
// Complex queries
$activeUsers = User::Query()
->filters([
'age' => ['gte' => 18, 'lte' => 65],
'status' => ['in' => ['active', 'premium']],
'email' => ['contains' => '@gmail.com']
])
->sort('created_at:desc')
->toArray();
// Get first record
$firstUser = User::Query(['status' => 'active'])->first();
```
#### Updating Records
```php
// Single record update
$user = User::Get(1);
$user->name = 'Updated Name';
$user->email = 'updated@example.com';
$user->save();
// Batch update
$affected = User::Query(['status' => 'inactive'])
->update(['status' => 'archived']);
```
#### Deleting Records
```php
// Single record deletion
$user = User::Get(1);
$user->delete();
// Batch deletion
$deleted = User::Query(['status' => 'spam'])
->delete();
```
### ๐ Advanced Queries
#### Query Conditions
```php
$query = User::Query()->filters([
'age' => ['eq' => 25], // Equal to
'score' => ['gt' => 80], // Greater than
'salary' => ['gte' => 50000], // Greater than or equal
'rating' => ['lt' => 5], // Less than
'points' => ['lte' => 100], // Less than or equal
'status' => ['in' => ['active', 'premium']], // In array
'name' => ['contains' => 'john'], // Contains pattern
'category' => ['ne' => 'spam'] // Not equal
]);
```
#### Sorting and Limiting
```php
$users = User::Query()
->sort('created_at:desc,name:asc') // Multi-field sorting
->limit(10) // Limit results
->offset(20) // Offset
->toArray();
```
#### Aggregate Functions
```php
$userCount = User::Query()->count();
$avgAge = User::Query()->avg('age');
$totalSalary = User::Query()->sum('salary');
$minAge = User::Query()->min('age');
$maxAge = User::Query()->max('age');
```
### ๐ Pagination
```php
$query = User::Query(['status' => 'active']);
$paginator = $query->getPaginator();
// Set items per page
$paginator->setItemCountPerPage(20);
$paginator->setCurrentPageNumber(1);
// Get current page data
$currentItems = $paginator->getCurrentItems();
$totalItems = $paginator->getTotalItemCount();
$totalPages = $paginator->getPages()->pageCount;
```
### ๐ JSON Field Operations
```php
// Create record with JSON data
$user = User::Create([
'name' => 'John',
'profile' => [
'avatar' => 'avatar.jpg',
'settings' => [
'theme' => 'dark',
'notifications' => true
],
'tags' => ['developer', 'php', 'mysql']
]
]);
$user->save();
// Read JSON data
$user = User::Get(1);
echo $user->profile['settings']['theme']; // 'dark'
// Update JSON data
$user->profile['settings']['theme'] = 'light';
$user->profile['tags'][] = 'javascript';
$user->save();
```
### ๐ Relationship Queries
```php
// Assuming UserList model with user_id column
$user = User::Get(1);
// Get related UserList query object
$userLists = $user->UserList; // Returns Query object
// Further querying
$activeLists = $user->UserList
->filters(['status' => 'active'])
->sort('created_at:desc')
->toArray();
```
### ๐ ๏ธ Advanced Features
#### Collection Operations
```php
$users = User::Query(['status' => 'active']);
// Map operation
$names = $users->map(fn($user) => $user->name)->toArray();
// Filter operation
$premiumUsers = $users->filter(fn($user) => $user->type === 'premium');
// Method chaining
$emailList = User::Query()
->filters(['status' => 'active'])
->map(fn($user) => $user->email)
->toArray();
```
#### Custom Sorting
```php
// Register custom sorting logic
User::RegisterOrder('popular', function($query) {
return $query->order(['score DESC', 'views DESC']);
});
// Use custom sorting
$popularUsers = User::Query()->sort('popular')->toArray();
```
## ๐ Available Test Groups
This project includes a comprehensive test suite. You can run specific test groups:
```bash
# Run all tests
composer test
# Run basic functionality tests
composer test-basic
# Run CRUD operation tests
composer test-crud
# Run JSON field tests
composer test-json
# Run unit tests
composer test-unit
# Run integration tests
composer test-integration
```
## ๐งช Test Coverage
- **73+** test cases
- **269+** assertions
- Covers all core functionality
- Includes unit and integration tests
- Supports error handling and edge case testing
## ๐ License
This project is licensed under the [MIT License](LICENSE).
## ๐จโ๐ป Author
**Raymond Chong**
- Email: mathsgod@yahoo.com
- GitHub: [@mathsgod](https://github.com/mathsgod)
## ๐ค Contributing
Issues and Pull Requests are welcome!
1. Fork the project
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
## ๐ More Examples
Check the test files in the `tests/` directory for more usage examples and best practices.