piko / db-record
A lightweight Active Record helper built on top of PDO.
Requires
- php: >=8.1.0
- piko/core: ^2.2
Requires (Dev)
- phpstan/phpstan: ^1.8
- phpunit/phpunit: ^10.5
- squizlabs/php_codesniffer: ^3.5
README
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.
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:
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:
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:
// See https://www.php.net/manual/en/class.pdo.php $db = new PDO('sqlite::memory:'); $query = <<<EOL CREATE TABLE contact ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, `order` INTEGER ) EOL; $db->exec($query);
Perform CRUD Operations
Create
Create a new record and save it to the database:
$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:
$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:
$contact->delete(); print_r($st->fetchAll()); // Array()
Support
If you encounter any issues or have questions, feel free to open an issue on GitHub.