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
It's recommended that you use Composer to install Piko Db Record.
composer require piko/db-record
https://piko-framework.github.io/docs/db-record.html
First, ensure you have the necessary autoloading in place:
require 'vendor/autoload.php';
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;
}
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);
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
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 a record from the database:
$contact->delete();
print_r($st->fetchAll()); // Array()
If you encounter any issues or have questions, feel free to open an issue on GitHub.