https://github.com/piko-framework/db-record
A lightweight Active Record implementation built on top of PDO
https://github.com/piko-framework/db-record
Last synced: 6 months ago
JSON representation
A lightweight Active Record implementation built on top of PDO
- Host: GitHub
- URL: https://github.com/piko-framework/db-record
- Owner: piko-framework
- License: lgpl-3.0
- Created: 2022-10-03T13:23:56.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2025-01-20T10:09:47.000Z (over 1 year ago)
- Last Synced: 2025-04-12T10:13:18.618Z (about 1 year ago)
- Language: PHP
- Homepage:
- Size: 53.7 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.txt
Awesome Lists containing this project
README
# Piko Db Record
[](https://github.com/piko-framework/db-record/actions/workflows/php.yml)
[](https://coveralls.io/github/piko-framework/db-record?branch=main)
Piko Db Record is a lightweight Active Record implementation built on top of PDO.
It has been tested and works with the following databases:
- SQLite
- MySQL
- PostgreSQL
- MSSQL
## Installation
It's recommended that you use Composer to install Piko Db Record.
```bash
composer require piko/db-record
```
## Documentation
https://piko-framework.github.io/docs/db-record.html
## Usage
First, ensure you have the necessary autoloading in place:
```php
require 'vendor/autoload.php';
```
### Define Your Model
Use the `Piko\DbRecord`, `Piko\DbRecord\Attribute\Table`, and `Piko\DbRecord\Attribute\Column`
classes to define your model. For example:
```php
use Piko\DbRecord;
use Piko\DbRecord\Attribute\Table;
use Piko\DbRecord\Attribute\Column;
#[Table(name:'contact')]
class Contact extends DbRecord
{
#[Column(primaryKey: true)]
public ?int $id = null;
#[Column]
public $name = null;
#[Column]
public ?int $order = null;
}
```
### Setup Database Connection
Create a new PDO instance and set up your database schema:
```php
// See https://www.php.net/manual/en/class.pdo.php
$db = new PDO('sqlite::memory:');
$query = <<exec($query);
```
### Perform CRUD Operations
#### Create
Create a new record and save it to the database:
```php
$contact = new Contact($db);
$contact->name = 'John';
$contact->order = 1;
$contact->save();
echo "Contact id : {$contact->id}"; // Contact id : 1
```
#### Read
Retrieve records from the database:
```php
$st = $db->prepare('SELECT * FROM contact');
$st->execute();
$rows = $st->fetchAll(PDO::FETCH_CLASS, Contact::class, [$db]);
print_r($rows); // Array ([0] => Contact Object(...))
// Load a single record by primary key:
$contact = (new Contact($db))->load(1);
var_dump($contact->name); // John
```
#### Delete
Delete a record from the database:
```php
$contact->delete();
print_r($st->fetchAll()); // Array()
```
## Support
If you encounter any issues or have questions, feel free to open an issue on GitHub.